map默认是0;如果不赋值就是0;
这类题是哈希表的特殊应用,一般hash表用来统计频次,这类题核心
在由若干 0 和 1 组成的数组 A 中,有多少个和为 S 的非空子数组。
示例:
输入:A = [1,0,1,0,1], S = 2
输出:4
解释:
如下面黑体所示,有 4 个满足题目要求的子数组:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
// #include<unordered_map>
class Solution
{
public:
int numSubarraysWithSum(vector<int>& A,int S)
{
//mp存储
unordered_map<int,int> mp;
//ans最后结果
int ans=0,tmp=0;
//前缀为0的目前有一个
mp[0]++;
for(auto x:A)
{
//依次遍历天然带有先后顺序
//当前节点的前缀总和
tmp+=x;
//tmp-S 在此之前i<j&&s[j]-s[i]=S mp[tmp-S]的值有几个
ans+=mp[tmp-S];
//当前和为tmp的加一个
mp[tmp]++;
}
return ans;
}
};
愿为天下目,萃聚六路华
浙公网安备 33010602011771号