zoukankan      html  css  js  c++  java
  • Leetcode** 209. Minimum Size Subarray Sum

    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

  • 相关阅读:
    简单工厂设计模式
    MVC备忘
    在MVC后台代码中想实现删除时弹出"确认删除"效果
    集合
    嵌套
    整理 补课内容
    百鸡百钱
    ////输入一个100以内的数,判断是不是正整数;
    课后题 5 6
    课后题3,4
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14655390.html
Copyright © 2011-2022 走看看