[leetcode] 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].

这道题是统计相加和为k的连续子数组个数,题目难度为Medium。

题目和第523题有些类似,感兴趣的同学可以顺便看下第523题(传送门)。

最直观的想法是遍历数组并依次加当前位置的数字,同时用数组sum记录下当前位置之前所有数字的相加和,这样下标[i, j)之间的数字之和就可以用sum[j]-sum[i]来计算,然后通过双层循环,遍历所有情况来统计满足条件的子数组个数。具体代码:

class Solution {
public:
    int subarraySum(vector& nums, int k) {
        int sz = nums.size(), cnt = 0;
        vector sum(sz+1, 0);
        for(int i=0; i

用sum表示从数组开始位置到当前位置的数字相加和,有了第523题的经验,我们还可以用Hash Table来存储sum出现的次数,如果当前位置之前有相加和为sum-k的位置,则这两个位置之间的数字相加和为k,以当前位置结尾的相加和为k的子数组个数为hash[sum-k],这样遍历整个数组即可得出满足条件的子数组个数。具体代码:

class Solution {
public:
    int subarraySum(vector& nums, int k) {
        int sum = 0, cnt = 0;
        unordered_map hash;
        
        hash[0] = 1;
        for(auto n:nums) {
            sum += n;
            cnt += hash[sum-k];
            ++hash[sum];
        }
        
        return cnt;
    }
};

你可能感兴趣的:(leetcode)