2019-10-22

560. Subarray Sum Equals K--Cumulative Sum

Descriptions:

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:
Input:nums = [1,1,1], k = 2
Output: 2

Analysis:

We can use a hash map to update the frequency of current sum with hash_map[cur_sum]++, and doing res+= hash_map[cur_sum-k] would give the answer we desire. NB: hash_map[0] = 1 before traversal !!!
Time O(n), space O(n);

class Solution {
public:
   int subarraySum(vector<int>& nums, int k) {
       unordered_map<int, int> m;
       int res=0, sum=0;
       m[0]=1;
       for(int ele:nums){
           sum+=ele;
           res += m[sum-k];
           m[sum]++;
       }
       return res;
   }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容