2019-10-22

作者: NeverFade | 来源:发表于2019-10-22 01:28 被阅读0次

    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;
       }
    };
    

    相关文章

      网友评论

        本文标题:2019-10-22

        本文链接:https://www.haomeiwen.com/subject/jkrfvctx.html