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:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
思路:暴力求解存在大量的重复计算,比如:在下标为0的时候,运算过 nums[0] + nums[1] + nums[2],在下标为1的时候,又算了一次nums[1] + nums[2]。
但是,采用累加和的方式:nums[1] + nums[2] = sum[2] - sum[0],只需要遍历一次就可以知道所有的前缀和,存在map里,用的时候就可以实现在常数时间的查找。
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int cur = 0, res = 0;
unordered_map<int, int> um;
// 注意这里前缀和多了一个0,防止漏掉数组的前缀和刚好等于k的情况
um[0] = 1;
for (int num : nums) {
cur += num;
res += um.find(cur - k) == um.end() ? 0 : um[cur - k];
++um[cur];
}
return res;
}
};
只需要遍历一次就可以知道所有的前缀和,存在map里,用的时候就可以实现在常数时间的查找。