题目描述:
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].
找到数组中的所有子数组,满足子数组之和等于目标值k。先计算[0,i]区间的数组累积和,那么对于当前的累计和sum,如果之前有x个累计和等于sum-k,那么就能找到x个子数组之和等于k,所以在每次计算累积和时,还要用哈希表存储累积和对应的次数。
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int sum=0;
unordered_map<int,int> hash;
hash[0]=1;
int count=0;
for(int i=0;i<nums.size();i++)
{
sum+=nums[i];
count+=hash[sum-k];
hash[sum]++;
}
return count;
}
};