209. 长度最小的子数组

2020-07-06  本文已影响0人  Chiduru

【Description】
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例:

输入:s = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。

【Idea】
数组子集, 常用双指针解, 比较具象
left, right标记当前的左右index,right右移到大于s的位置,比较一次更新result
之后再执行left右移操作至当前和小于s。

思路不难想, 实现的细节一直报错,哎

【Solution】

class Solution:
    def minSubArrayLen(self, s: int, nums: List[int]) -> int:
        if not nums:
            return 0
        
        n = len(nums)
        ans = n + 1        
        start, end = 0, 0
        total = 0
        while end < n:
            total += nums[end]
            while total >= s:
                ans = min(ans, end - start + 1)
                total -= nums[start]
                start += 1
            end += 1
        
        return 0 if ans == n + 1 else ans

上一篇下一篇

猜你喜欢

热点阅读