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
.
----------------------------------------------------------------------------------
题目非常简单,前缀法很容易想到,但是前缀是否为空是前缀法的常见bug,第一次提交不幸入坑。正确代码是:
class Solution:
def numSubarraysWithSum(self, A, S: int) -> int:
dic, l, cursum, res = {0: 1}, len(A), 0, 0 # bug2:dic={}
for i in range(l):
cursum += A[i]
# prefix + subarray(S) = cursum, so the number of prefixes dominate # of S
res += dic.get(cursum - S, 0)
dic[cursum] = dic.get(cursum, 0) + 1
return res # bug1: add dic.get(cursum-S,0)
但是前缀法并没有利用0,1的条件,有了0,1的限制,刚好搞一个非递减序列,因此可以用尺取法,但是由于是非递减,尺子前后都可能是0,堪称大坑,很容易写bug,好不容易写对了,复杂度还可能退化到O(n^2)。
一个比较好的思路是转换成两个小等于的差,以下是codes:
class Solution:
def at_most(self, A, S):
if (S < 0):
return 0
la,i,cursum,res = len(A),0,0,0
for j in range(la):
cursum += A[j]
while (cursum > S):
cursum -= A[i]
i += 1
res += (j-i+1)
return res
def numSubarraysWithSum(self, A, S: int) -> int:
return self.at_most(A,S)-self.at_most(A,S-1)