108th LeetCode Weekly Contest Binary Subarrays With Sum

Posted 樱花落舞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了108th LeetCode Weekly Contest Binary Subarrays With Sum相关的知识,希望对你有一定的参考价值。

In an array A of 0s and 1s, 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:

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. A[i] is either 0 or 1.

通用解法就是求连续数组的和有多少个,这种题代码都不会变的

把和存起来,给后面的数字-S看有没有这个和,有的话加起来,然后a[ans]++说明又存在符合条件的解了

class Solution {
public:
    int numSubarraysWithSum(vector<int>& A, int S) {
       long long ans = 0;
       long long k=0;
       map<long long,long long>a;
       a[0]=1;
       int len = A.size();
       for(int i=0;i<len;i++){
        ans+=A[i];
        if(ans>=S){
            k+=a[ans-S];
        }
        a[ans]++;
       }
       return k;
    }
};

 

以上是关于108th LeetCode Weekly Contest Binary Subarrays With Sum的主要内容,如果未能解决你的问题,请参考以下文章

123th LeetCode Weekly Contest Broken Calculator

118th LeetCode Weekly Contest Pancake Sorting

113th LeetCode Weekly Contest Flip Equivalent Binary Trees

113th LeetCode Weekly Contest Reveal Cards In Increasing Order

116th LeetCode Weekly Contest Maximum Width Ramp

113th LeetCode Weekly Contest Largest Time for Given Digits