和相同的二元子数组
https://www.lintcode.com/problem/1712/description?utm_source=sc-cheatsheet-cyc
输入:A = [1,0,1,0,1], S = 2输出:4解释:如下面黑体所示,有 4 个满足题目要求的子数组:[1,0,1][1,0,1][1,0,1,0][0,1,0,1]输入:A = [0,0,0,0,0,0,1,0,0,0], S = 0输出:27解释:和为 S 的子数组有 27 个 count += prefix_count[prefix_sum - S]
```python
from typing import (
List,
)
class Solution:
"""
@param a: an array
@param s: the sum
@return: the number of non-empty subarrays
"""
def num_subarrays_with_sum(self, a: List[int], s: int) -> int:
# Write your code here.
presum = {0:1} #某个sum出现的次数
cursum = 0
res = 0
for i in a:
cursum += i
if cursum - s in presum:
res += presum[cursum - s]
presum[cursum] = presum.get(cursum, 0) + 1
return res
```Last updated