Leetcode 209. Minimum Size Subarray Sum

本文介绍了一种使用滑动窗口算法解决寻找满足特定条件的最短子数组问题的方法。通过双指针技巧,逐步调整窗口大小,高效地找到目标子数组。此算法适用于正数数组,并详细展示了其实现过程。

思路一: 本题nums里面的数由于都是正数,所以可以用两个指针 start 和 end = 0。end++向后寻找,直到 start和end之间的sum>=s。例如 nums = [2, 3, 1, 2, 4, 3], s = 7。这一步结束时找到了start = 0 的最短的满足条件的subarray。

显然当前的这个解可能不是以end = 3的最优解,所以start++,直到total < 7。

这时我们又需要end++,直到total>=s来寻找以start = 1开头的最短subarray。

 1 class Solution(object):
 2     def minSubArrayLen(self, s, nums):
 3         """
 4         :type s: int
 5         :type nums: List[int]
 6         :rtype: int
 7         """
 8         size = len(nums)
 9         if size == 0:
10             return 0
11         left = right = 0
12         total = 0
13         res = size + 1
14         
15         while right < size:
16             while total < s and right < size:
17                 total += nums[right]
18                 right += 1
19             while left < right and total >= s:
20                 res = min(res, right - left)
21                 total -= nums[left]
22                 left += 1
23                 
24         return res if res <= size else 0

 

转载于:https://www.cnblogs.com/lettuan/p/6361182.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值