首页 > 其他 > 详细

Leetcode** 209. Minimum Size Subarray Sum

时间:2021-04-14 01:47:26      阅读:13      评论:0      收藏:0      [点我收藏+]

Description: Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Link: 209. Minimum Size Subarray Sum

Examples:

Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1

Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

思路: O(n)复杂度,只遍历一遍,不会啊,没思路。这个视频讲解的很好。首先left=0,然后right指针从0向后移,直到sum(nums[l:r+1]) >= target,然后让left从0向右移,缩小这个sum>=target的区间,更新最小区间的值,直到缩小到其和小于target, 然后right指针再开始右移,循环此过程,直到right指针到nums的尾。

class Solution(object):
    def minSubArrayLen(self, target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        l, s = 0, 0
        res = float("inf")
        for i in range(len(nums)):
            s += nums[i]
            while l <= i and s >= target:
                res = min(res, i-l+1)
                s -= nums[l]
                l += 1
        if res == float("inf"):
            return 0
        return res

日期: 2021-04-13

Leetcode** 209. Minimum Size Subarray Sum

原文:https://www.cnblogs.com/wangyuxia/p/14655390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!