Leetcode WC-108-02 930-和相同的二元子数组

2018.10.28 12:00

在由若干 0 和 1  组成的数组 A 中,有多少个和为 S 的非空子数组。

 

示例:

输入:A = [1,0,1,0,1], S = 2
输出:4
解释:
如下面黑体所示,有 4 个满足题目要求的子数组:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

 

提示:

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. A[i] 为 0 或 1

分析:

  暂无

 1 # python3
 2 
 3 class Solution:
 4     def numSubarraysWithSum(self, A, S):
 5         """
 6         :type A: List[int]
 7         :type S: int
 8         :rtype: int
 9         """
10         dit={}
11         tmp=res=0
12         for a in A:
13             dit.setdefault(tmp,0)
14             dit[tmp]+=1
15             tmp+=a
16             dit.setdefault(tmp-S,0)
17             res+=dit[tmp-S]
18         return res
原文地址:https://www.cnblogs.com/tenjl-exv/p/9865041.html