题目链接: https://leetcode-cn.com/problems/subarray-sum-equals-k/
使用方法: 前缀和数组以及哈希化
使用前缀和保证性质: 对于[i…j], 如果满足和为K, 那么pre[j] = pre[i - 1] + k, 即pre[i - 1] = pre[j] - k
当遍历到j时, 我们只需要知道有多少个i满足这个性质, 那么就要多少个以j结尾的子数组满足和为K, 因此引入哈希表用于保存i的状态
class Solution {
public:
unordered_map<int, int> map;
int subarraySum(vector<int>& nums, int k) {
map[0] = 1;
int pre = 0;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
pre += nums[i];
if (map[pre - k]) count += map[pre - k];
if (map[pre]) map[pre]++;
else map[pre] = 1;
}
return count;
}
};