知识点总结
- 为什么不采用滑动窗口而采用前缀和+哈希表?
因为,该数组中含有负数,若以枚举low指针方法找子串,high指针有些时候需要左移。所以不能使用。
对应的代码和注释:
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
map<int, int> mp;
mp[0] = 1;
int pre = 0,ans=0;
for (auto n : nums)
{
pre += n;
if (mp.find(pre-k)!=mp.end())
{
ans += mp[pre - k];//记录n元素结尾的子串满足和要求的个数
}
mp[pre]++;//先找再将本身前缀和存于map容器
}
return ans;
}
};