题目:
给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 的 非空 子数组。
子数组 是数组的一段连续部分。

思路:
滑动窗口
解答:
方法一:
class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
#求数组A中 元素和小于等于target的连续子数组 的个数
def atMostK(A, target):
if target<0:
return 0
res=0
left,right=0,0
n=len(A)
while right<n:
target -= A[right]
#窗口滑动
while target< 0:
target += A[left]
left += 1
res += right-left + 1
#窗口拓展
right+=1
return res
return atMostK(nums, goal) - atMostK(nums, goal - 1)
方法二:
class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
#求数组A中 元素和小于等于target的连续子数组 的个数
def atMostK(A, target):
if target<0:
return 0
res=0
left,right,total=0,0,0
n=len(A)
while right<n:
total+=A[right]
#窗口滑动
while total>target:
total-= A[left]
left += 1
res += right-left + 1
#窗口拓展
right+=1
return res
return atMostK(nums, goal) - atMostK(nums, goal - 1)

这篇博客介绍了如何利用滑动窗口算法解决寻找数组中和为特定目标值的非空子数组数量的问题。提供了两种不同的实现方法,通过维护窗口内的元素和来动态调整窗口边界,从而统计符合条件的子数组个数。

227

被折叠的 条评论
为什么被折叠?



