给定一个数组 nums 和一个正整数 target , 找出满足和大于等于 target 的长度最短的连续子数组并返回其长度,如果不存在这种子数组则返回 0。
数据范围:数组长度满足 ,数组中的元素满足 ,
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param nums int整型一维数组 # @param target int整型 # @return int整型 # class Solution: def minSubarray(self , nums: List[int], target: int) -> int: # write code here left = 0 right = 0 sum = 0 min_len = len(nums) found = False # 采用左闭右开的方式 while left < len(nums): # sum不够则伸长 if sum < target: if right < len(nums): sum += nums[right] right += 1 else: break # 查看值并开始缩减长度 else: found = True min_len = min(min_len, right - left) sum -= nums[left] left += 1 if found: return min_len else: return 0