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;
}
};