LeetCode 930. Binary Subarrays With Sum

原题链接在这里:https://leetcode.com/problems/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.

题解:

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 }

 

posted @ 2019-08-23 00:43  Dylan_Java_NYC  阅读(362)  评论(0编辑  收藏  举报