题目
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
解题思路:
思路:确定数组中的start和end,使start到end之间的数加起来和大于target。
-
暴力解法
第一想法就是使用双层循环,第一层为start,第二层为end,遍历数组,找到符合条件且长度最小的。from numpy import Inf class Solution(object): def minSubArrayLen(self, target, nums): """ :type target: int :type nums: List[int] :rtype: int """ # 暴力解法,双层循环 result = Inf # 结果赋最大值 len1 = len(nums) for i in range(len1): sum = 0 for j in range(i, len1): sum += nums[j] if sum >= target: # 使用较小长度值更新result result = min(j - i + 1, result) break # 不存在时返回0,存在时返回result return 0 if result == Inf else result
-
滑动窗口
start和end以窗口的形式向前移动,通过改变窗口的大小取得最小长度值。from numpy import Inf class Solution(object): def minSubArrayLen(self, target, nums): """ :type target: int :type nums: List[int] :rtype: int """ # 滑动窗口 result = Inf len1 = len(nums) sum = 0 start = 0 for i in range(len1): sum += nums[i] # 在满足和大于等于target的条件下,向前移动start,减小子数组长度 while sum >= target: result = min(result, i- start + 1) sum -= nums[start] start += 1 return 0 if result == Inf else result