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].
题目链接:https://leetcode-cn.com/problems/subarray-sum-equals-k/
思路
常用套路:前缀和,计算下标0~i的元素之和,但记录时是由和 查找前缀个数。
对于 当前数值nums[i] 和 当前和sum,如果存在 sum-前缀和j=k,则说明j~i段为所求连续子串。
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int len = nums.size();
if(len==0) return 0;
unordered_map<int, int> pre;
pre[0] = 1;
int sum = 0, res = 0;
for(int i=0; i<len; ++i){
sum += nums[i];
res += pre[sum-k];
++pre[sum];
}
return res;
}
};