Python教程

Leetcode:209. 长度最小的子数组(Python3)

本文主要是介绍Leetcode:209. 长度最小的子数组(Python3),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        # 边界条件
        if not nums or len(nums) == 0:
            return 0
        left, right = 0, 0
        total, result = 0, len(nums)+1
        # 滑动
        while right < len(nums):
            total += nums[right]
            right += 1
            while total >= target:
                result = min(result, right-left)
                total -= nums[left]
                left += 1
        # 返回结果
        return result if result != len(nums)+1 else 0

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        # 边界条件
        if not nums or len(nums) == 0:
            return 0
        total, result = 0, len(nums)+1
        for left in range(len(nums)):
            total = 0
            for right in range(left,len(nums)):
                total += nums[right]
                if total >= target:
                    result = min(result, right-left+1)
                    break
        return result if result != len(nums)+1 else 0

这篇关于Leetcode:209. 长度最小的子数组(Python3)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!