209. Minimum Size Subarray Sum

问题描述

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

问题分析

思路是滑动解决。
设置left、right两个指针,total记录下标在left到right之间的数字的和。起始left、right均置为0,向后移动right,直至total大于等于s;向后移动left,直至total<s,此时right-left+1为subarray的长度。交替移动right和left,直到right到达末尾。

AC代码

class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n == 0:
            return 0
        left = right = total = 0
        opt = n+1
        while right < n:
            while right < n and total < s:
                total += nums[right]
                right += 1
            if total < s:
                break
            while left < right and total >= s:
                total -= nums[left]
                left += 1
            if right - left + 1 < opt:
                opt = right - left + 1
        return opt if opt <= n else 0

Runtime: 52 ms, which beats 68.97% of Python submissions.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容