LeetCode 209 Minimum Size Subarray Sum 题目解析和python代码

题目:

Given an array of positive integers nums and a positive integer target, return the minimal length of a

subarray

whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Example 1:

Input: target = 7, nums = [2,3,1,2,4,3]

Output: 2

Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

Input: target = 4, nums = [1,4,4]

Output: 1

Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]

Output: 0

Constraints:

1 <= target <= 109

1 <= nums.length <= 105

1 <= nums[i] <= 104

Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).

题目解析:

这里我们可以使用 sliding window 的技巧。

我们可以使用两个 pointers,一个是 start 一个是 end,两个指针都从array的开头开始。

向右移动 end 指针来提高 window 的大小,每一次移动指针都把 nums[end] 添加到现在的和。

当这个和大于或等于 target 时,我们要开始缩短 subarray 的长度。于是我们开始移动 start 这个指针来缩小 window 的大小。通过不停的向右移动 start 指针,直到找到最短的 subarray 的长度。

python 复制代码
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        start = 0
        curr_sum = 0
        min_len = float('inf')

        for end in range(len(nums)):
            curr_sum += nums[end]

            while curr_sum >= target:
                min_len = min(min_len, end - start + 1)
                curr_sum -= nums[start]
                start += 1
            
        return min_len if min_len != float('inf') else 0

Time complexity 是 O(n)。

Space complexity 是 O(1)。

相关推荐
云动雨颤几秒前
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
python·单元测试
skytier4 分钟前
Construct内报错和定位解决
算法
skytier9 分钟前
Ascend print数据落盘使用
算法
SunnyDays101121 分钟前
Python 实现 HTML 转 Word 和 PDF
python·html转word·html转pdf·html转docx·html转doc
etcix24 分钟前
dmenux.c: integrate dmenu project as one file
c语言·前端·算法
papership25 分钟前
【入门级-算法-6、排序算法:选择排序】
数据结构·算法·排序算法
汉克老师1 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(4、最大空白区)
c++·算法·蓝桥杯·蓝桥杯c++·c++蓝桥杯
共享家95271 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
跟橙姐学代码1 小时前
Python异常处理:告别程序崩溃,让代码更优雅!
前端·python·ipython
一只懒洋洋1 小时前
中值滤波、方框滤波、高斯滤波、均值滤波、膨胀、腐蚀、开运算、闭运算
算法·均值算法