当前位置: 首页 > news >正文

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 的长度。

class Solution:def minSubArrayLen(self, target: int, nums: List[int]) -> int:start = 0curr_sum = 0min_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 += 1return min_len if min_len != float('inf') else 0

Time complexity 是 O(n)。
Space complexity 是 O(1)。

http://www.lryc.cn/news/455408.html

相关文章:

  • C# 入坑JAVA 潜规则 注解 列表 listMch,该列表存储了一个映射(Map)的集合 等 入门系列3
  • 2024年9月个人工作生活总结
  • JVM有哪些参数以及如何使用
  • STM32编码器接口解析及抗噪声措施探讨
  • 微软发布Windows 11 2024更新,新型Copilot+ AI PC功能亮相
  • 鹏哥C语言68-70---位操作符+单目操作符+关系操作符
  • showdoc二次开发
  • 力扣16~20题
  • Pikachu-Sql-Inject -基于boolian的盲注
  • 最后30天,你的系统集成项目管理工程师备考进度到哪儿了?
  • 网络安全事件的发生,主要原因是什么
  • 【leetcode】274.H指数
  • 1.Python 引入(字面量、注释、变量、数据类型、数据类型转换、标识符、运算符、字符串扩展)
  • 【AI知识点】梯度消失(Vanishing Gradient)和梯度爆炸(Exploding Gradient)
  • 在 ArkTS 网络请求中,重新封装一下 http 模块
  • Microsoft 更新 Copilot AI,未來將能使用語音並看到你瀏覽的網頁
  • 系统架构设计师-论文题(2021年下半年)
  • selenium的webdriver常用方法和属性介绍(2)
  • 73.【C语言】C/C++的内存区域划分
  • k8s 中存储之 hostPath 卷
  • Cherno游戏引擎笔记(73~90)
  • helm 测试卸载或删除(redis)
  • 关于Qt音乐播放器进度条拖拽无用的问题解决方案
  • Redis:初识Redis
  • 【React】增量传输与渲染
  • 【回眸】Tessy 单元测试软件使用指南(四)常见报错及解决方案与批量初始化的经验
  • 2024 - 10 :生物药学: 如何获取对应核心靶点基因的激酶
  • STM32 HAL库UART查询方式实例
  • 数据结构--线性表双向链表的实现
  • 第一个Flutter应用(一)