209. 长度最小的子数组

之前用暴力求解超时了,改为双指针滑窗就好了

class Solution:
    def minSubArrayLen(self, target, nums):
        n = len(nums)
        ans = n + 1
        left = 0  # 左指针
        temp = 0  # num[left:i+1]的累加和
        for i in range(n):  # i为右指针
            temp += nums[i]
            while temp >= target:
                ans = min(ans, i - left + 1)
                temp -= nums[left]
                left += 1
        if ans == n + 1:
            return 0
        else:
            return ans


target = 7
nums = [2,3,1,2,4,3]
print(Solution().minSubArrayLen(target, nums))

你可能感兴趣的:(力扣,python,数据结构)