题目描述
In an array A of 0s and 1s, how many non-empty subarrays have sum S?
Example 1:
1 | Input: A = [1,0,1,0,1], S = 2 |
Note:
- A.length <= 30000
- 0 <= S <= A.length
- A[i] is either 0 or 1
解析
题目是在一个由0、1组成的序列中,找到和为S的subarray的个数。
所有subarray的题目都可以考虑用prefix sum进行优化,即sum(i ,j) = prefix(j) - prefix(i)对于本题而言,可以利用HashMap存储prefix为特定sum的序列个数,每次有X新的元素加入的时候,更新即可,代码如下
1 | public int numSubarraysWithSum(int[] A, int S) { |