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 <= numsi <= 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 的大小,每一次移动指针都把 numsend 添加到现在的和。

当这个和大于或等于 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)。

相关推荐
xys_6788 分钟前
深挖数据结构:树和二叉树(上)
数据结构·算法
Merrill_hh19 分钟前
Python环境搭建
python
用户0190275816124 分钟前
如何用 Python 回测布林带突破策略?
python
Interview Aid11232 分钟前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法
4SAPI34 分钟前
企业Agent落地选型:大模型API接入方案迁移实践与稳定性评估
人工智能·python·php
用户019027581611 小时前
如何用 Python 计算 CR 能量指标(中间意愿指标)?
python
曲径海盗1 小时前
【Python 学习第 34 天】条件判断 if/else
python·学习笔记·编程入门
用户6602676118791 小时前
重试不重复下单还不够:同一幂等键换了参数,应该返回什么?
python
五网1 小时前
用Python搭建创业项目财务测算模型:CAC、LTV、盈亏平衡点一键算出(附完整代码)
python
琳达爱分享1 小时前
从单机令牌桶到集群限流:一次配额超发的复盘
后端·算法