Given an array of positive integers nums and a positive integer target, return the minimal length of a
subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
思路:思路其实很简单,就是维护一个动态的滑动窗口,我感觉大家都会这么想吧。看了题解后,发现似乎官方都不是一开始用的滑动窗口!我们可以通过一个窗口来维持里面的数的和始终小于target,不断往里面增加数字,大于等于target时,就需要移动左边的指针,不断缩减,因为我们的目标是求得最短的,所以要是的窗口的区间足够小。
class Solution:def minSubArrayLen(self, s: int, nums: List[int]) -> int:n=len(nums)l=0res=float("inf")tmp=0for r in range(n):tmp+=nums[r]while(tmp>=s):res=min(res,r-l+1)tmp-=nums[l]l+=1return res if(res!=float("inf")) else 0