Skip to content

LeetCode #209:长度最小的子数组

https://leetcode.cn/problems/minimum-size-subarray-sum/description/

题目分析

这题是个标准的滑动窗口,不过我算法太久没写了,一直想用 if elif else 写,后来经过 GPT 老师指点之后发现有可能窗口长度一次可能可以缩减多个,所以这道题只能用 while

题解

python
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left = 0
        sum = 0
        ans = float("inf")

        for idx, i in enumerate(nums):
            sum += i

            while sum >= target:
                ans = min(ans, idx + 1 - left)
                sum -= nums[left]
                left += 1

        return 0 if ans == float("inf") else ans

页面历史

Powered by VitePress and Elysium UI.
This site uses Microsoft Clarity to see how you use our website. By using our site, you agree that we and Microsoft can collect and use this data.