930. Binary Subarrays With Sum
https://leetcode.com/problems/binary-subarrays-with-sum/
In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
Note:
A.length <= 30000
0 <= S <= A.length
A[i]
is either0
or1
Thoughts
给定二进制数组有多少子数组和为S。子数组和问题 => presum或sliding window。presum没有什么特别的。sliding window不是直接求解满足条件的子数组和,而是先求和为[0:S]的所有子数组个数,再求和为[0:S-1]的所有子数组个数,它俩的差为子数组和为S的个数。用sliding window求和为[0:S]的所有子数组个数实现简单。
思路参考自这。
Subarray sum == S想到用hash map依次遍历把所有的 presum存起来,然后类似背包看count[presum - S]的个数,再+到res上
注意应先更新res, 因为是presum表之前有没有出现过这个sum,再更新count[presum]个数。
Code
Last updated
Was this helpful?