一、题目
给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其总和大于等于 target
的长度最小的子数组
[numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
二、分析
滑动窗口的方法
错误1:对result的值没有考虑为0的情况
错误2:now_length的长度加1了——在进入第二个循环的时候,right已经指向了满足和为target的尾巴的后一个位置,所以不需要加1
三、代码
class Solution(object):def minSubArrayLen(self, target, nums):""":type target: int:type nums: List[int]:rtype: int"""left=0right=0sum=0result = float('inf')while right<len(nums):sum+=nums[right]right+=1while sum>=target:now_length=right-leftresult=min(result,now_length)sum=sum-nums[left]left+=1return result if result != float('inf') else 0