560. Subarray Sum Equals K

Posted qiang-wei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 

以上是关于560. Subarray Sum Equals K的主要内容,如果未能解决你的问题,请参考以下文章

560. Subarray Sum Equals K

560. Subarray Sum Equals K

560. Subarray Sum Equals K

560. Subarray Sum Equals K

560. Subarray Sum Equals K

560. Subarray Sum Equals K