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)。

相关推荐
jghhh015 分钟前
使用 MATLAB 实现支持向量回归 (SVR) 预测未来数据
算法·matlab
云泽80812 分钟前
笔试算法 - 双指针篇(二):四大经典求和题型 + 有效三角形计数问题
c++·算法
pele30 分钟前
PHP源码运行受主板供电影响吗_供电相数重要性说明【技巧】
jvm·数据库·python
sinat_3834373631 分钟前
CSS如何实现元素悬浮在页面底部_利用fixed定位与底部间距
jvm·数据库·python
gmaajt1 小时前
mysql如何备份与恢复函数定义_mysql mysqldump导出存储对象
jvm·数据库·python
qq_460978401 小时前
Python爬虫怎么模拟手机端抓取_设置手机型号User-Agent字符串
jvm·数据库·python
刀法如飞2 小时前
【合并已排序数组的三种实现策略,哪一种更可取?】
算法·程序员
love530love2 小时前
Clink 调校指南:让 Windows CMD 拥有现代终端的便捷体验
人工智能·windows·python·cmd·clink
王老师青少年编程2 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【区间贪心】:种树
c++·算法·贪心·csp·信奥赛·区间贪心·种树