LeetCode 930. Binary Subarrays With Sum
原题链接在这里:https://leetcode.com/problems/binary-subarrays-with-sum/
题目:
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
.
题解:
Maintian the count of sum from 0 to i.
If sum >= S, then res += count[sum-S].
Because, there must be t, t<i, sum from 0 to t is sum-S, from t to i is S. Then count of S is count of sum-S.
Time Complexity: O(n). n = A.length.
Space: O(n).
AC Java:
1 class Solution { 2 public int numSubarraysWithSum(int[] A, int S) { 3 if(A == null || A.length == 0){ 4 return 0; 5 } 6 7 int [] count = new int[A.length+1]; 8 count[0] = 1; 9 int sum = 0; 10 int res = 0; 11 for(int a : A){ 12 sum += a; 13 if(sum >= S){ 14 res += count[sum-S]; 15 } 16 17 count[sum]++; 18 } 19 20 return res; 21 } 22 }