https://leetcode.com/problems/subarray-sum-equals-k/description/
总觉得结合数据结构降低时间复杂度的题有点没意思。但是既然是比较长问的题还是准备下。。。。
参考了 https://leetcode.com/problems/subarray-sum-equals-k/discuss/102121/C++-prefix-sum-+-map
先ans += 后Rec[cur]++ 因为k = 0的情况
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> rec;
int ans = 0, cur = 0;
rec[0]++;
for (int i = 0; i < nums.size(); i++) {
cur += nums[i];
ans += rec[cur-k];
rec[cur] ++;
}
return ans;
}
};