Juice's blogs

2019-10-22

2019-10-22  本文已影响0人  NeverFade

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;
   }
};
上一篇下一篇

猜你喜欢

热点阅读