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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11397639.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值