题目
https://leetcode.com/problems/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
Constraints:
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].
思路
记录向前累计和,而后向前查找距离目标k的差值出现多少次,区间问题尽量转换为向前累计和的操作,而不是区间和的问题
源码
class Solution {
public:
unordered_map<int,int> m;
int sum[20005];
int res = 0;
int subarraySum(vector<int>& nums, int k) {
sum[0] = 0;
m[0] = 1;
for(int i = 1;i <= nums.size();++i){
int s = sum[i-1]+nums[i-1];
sum[i] = s;
int re = s-k;
if(m.find(re)!=m.end()){
res+=m[re];
}
if(m.find(s)==m.end()){
m[s]=1;
}else{
m[s]++;
}
}
return res;
}
};