560. Subarray Sum Equals K

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

 

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

方法1:双层遍历

。。。 

 

方法2:利用哈希表加一点数学推导

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int n = nums.size();
        if (n == 0) return 0;
        unordered_map<int, int>sum_fre;
        sum_fre[0] = 1;
        int sum = 0;
        int res = 0;
        for (auto num: nums)
        {
            sum += num;
            // k = sum[0, j] - sum[0, i - 1] ===> sum[0, j] - k  其中i-1 < j; 
            // 遍历一遍,将所有的sum[0, j]存起来。若在哈希表中发现之前有满足上边式子的,则得到一个满足要求的连续序列
            if (sum_fre.find(sum - k) != sum_fre.end())
                res += sum_fre[sum - k];
            sum_fre[sum]++;
        }
        return res;
    }
};

 

posted @ 2020-02-06 23:18  强威  阅读(150)  评论(0编辑  收藏  举报