Leetcode 930 Binary Subarrays With Sum (双指针)

Posted Will

tags:

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

Leetcode

问题描述

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]

方法一

** Solution Java **
** 2ms, beats 84.49% **
** 44MB, beats 25.00% **
class Solution {
    public int numSubarraysWithSum(int[] A, int S) {
        int n = A.length, res = 0, sum = 0;
        int[] map = new int[n + 1];
        map[0] = 1;
        for (int i = 0; i < n; ++i) {
            sum += A[i];
            if (sum >= S) 
                res += map[sum - S];
            ++map[sum];
        }
        return res;
    }
}

方法二

** Solution Java **
** 1ms, beats 100.00% **
** 44.3MB, beats 25.00% **
class Solution {
    public int numSubarraysWithSum(int[] A, int S) {
        return atMost(A, S) - atMost(A, S - 1);
    }
    private int atMost(int[] A, int S) {
        if (S < 0) 
            return 0;
        int res = 0, n = A.length;
        for (int i = 0, j = 0; j < n; ++j) {
            S -= A[j];
            while (S < 0) 
                S += A[i++];
            res += j - i + 1;
        }
        return res;
    }
}

以上是关于Leetcode 930 Binary Subarrays With Sum (双指针)的主要内容,如果未能解决你的问题,请参考以下文章

930. Binary Subarrays With Sum

LeetCode 930.和相同的二元子数组

LeetCode 930 和相同的二元子数组[动态规划 前缀和] HERODING的LeetCode之路

LeetCode 1764. 通过连接另一个数组的子数组得到一个数组

LeetCode 1764. 通过连接另一个数组的子数组得到一个数组

[LeetCode226]Invert Binary Tree