长度最小的子数组python3(leetcode209)

#209. 长度最小的子数组
#给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 
#连续子数组并返回其长度。如果不存在符合条件的子数组,返回 0。

连续子数组

#1 暴力解法

class Solution(object):
    def minSubArrayLen(target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        sub_arr, result = 0, float('inf')

        for i in range(0, len(nums)):
            sub_arr = 0 #子序列起点
            for j in range(i, len(nums)):
                sub_arr += nums[j] #满足if条件的子序列终点

                if (sub_arr >= target and j -i + 1 < result):
                    # 取子序列的长度
                    sub_length = j -i + 1
                    result = sub_length
                    break
        if result != float('inf'):
            return result
        else:
            return 0
a = Solution.minSubArrayLen(target = 10, nums = [1,2,3,4,5,3,2,3,2,5])

#2 滑动窗口

class Solution(object):
    def minSubArrayLen(self, target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        #滑动窗口
        left, right, result, sub_length, sub_sum= 0, 0, float('inf'), 0, 0

        while(right < len(nums)):
            sub_sum += nums[right] #滑动窗口
            right +=1 #移动right

            while(sub_sum >= target):
                sub_length = right - left
                result = min(sub_length, result)
                sub_sum -= nums[left]
                left += 1

        if result == float('inf'):
            return 0
        else:
            return result

猜你喜欢

转载自blog.csdn.net/ziqingnian/article/details/121808566