其他分享
首页 > 其他分享> > [专题1:数组]滑动窗口:209.长度最小的子数组

[专题1:数组]滑动窗口:209.长度最小的子数组

作者:互联网

题目描述:给定一个含有n个正整数的数组和一个正整数s,找出该数组中满足其和>=s的长度最小的连续子数组,并返回其长度。如果不存在符合条件的子数组,返回0。

def solve(nums, s):
    minlen = 0
    result = math.inf
    for i in range(len(nums)):
        sums = 0
        for j in range(i, len(nums)):
            sums += nums[j]
            if sums >= s:
                minlen = j - i + 1
                if result > minlen:
                    result = minlen
    return result

 

def minSubArrayLen(self, target, nums):
    """
    :type target: int
    :type nums: List[int]
    :rtype: int
    """

    startindex = 0
    result = float('inf')
    sums = 0
    if sum(nums) < target:
        return 0    
    for i in range(len(nums)):
        sums += nums[i]
        while sums >= target:
            minlen = i - startindex + 1
            result = min(result, minlen)
            sums -= nums[startindex]
            startindex += 1
    return result

 

标签:nums,209,minlen,sums,result,数组,长度,滑动
来源: https://blog.csdn.net/qq_37543361/article/details/121771001