
In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
Note:
A.length <= 30000
0 <= S <= A.length
-
A[i]
is either0
or1
.
通用解法就是求连续数组的和有多少个,这种题代码都不会变的
把和存起来,给后面的数字-S看有没有这个和,有的话加起来,然后a[ans]++说明又存在符合条件的解了
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S) {
long long ans = ;
long long k=;
map<long long,long long>a;
a[]=;
int len = A.size();
for(int i=;i<len;i++){
ans+=A[i];
if(ans>=S){
k+=a[ans-S];
}
a[ans]++;
}
return k;
}
};