当前位置:网站首页>【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
2022-08-03 19:24:00 【friedrichor】
剑指 Offer II 008. 和大于等于 target 的最短子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [ n u m s l , n u m s l + 1 , . . . , n u m s r − 1 , n u m s r ] [nums_l, nums_{l+1}, ..., nums_{r-1}, nums_r] [numsl,numsl+1,...,numsr−1,numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
提示:
- 1 < = t a r g e t < = 1 0 9 1 <= target <= 10^9 1<=target<=109
- 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
- 1 < = n u m s [ i ] < = 1 0 5 1 <= nums[i] <= 10^5 1<=nums[i]<=105
题解
滑动窗口
最简单的滑动窗口,不过这个超时了。
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
for window_size in range(1, len(nums) + 1):
for i in range(len(nums) + 1 - window_size):
sum_window = sum(nums[i: i + window_size])
if sum_window >= target:
return window_size
return 0
改进(双指针):
双指针left,right
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0
sum_window = 0
min_len = 1e5 + 1
for right, value in enumerate(nums):
sum_window += value
while sum_window >= target:
min_len = min(min_len, right - left + 1)
sum_window -= nums[left]
left += 1
return min_len if min_len <= 1e5 else 0
以 target = 7, nums = [2,3,1,2,4,3]
为例:
[2] 3 1 2 4 3 sum_window < target
[2 3] 1 2 4 3 sum_window < target
[2 3 1] 2 4 3 sum_window < target
[2 3 1 2] 4 3 sum_window >= target, min_len = 4
2 [3 1 2] 4 3 sum_window < target
2 [3 1 2 4] 3 sum_window >= target, min_len = 4
2 3 [1 2 4] 3 sum_window >= target, min_len = 3
2 3 1 [2 4] 3 sum_window < target
2 3 1 [2 4 3] sum_window >= target, min_len = 3
2 3 1 2 [4 3] sum_window >= target, min_len = 2
2 3 1 2 4 [3] sum_window < target
边栏推荐
猜你喜欢
随机推荐
阿里二面:多线程间的通信方式有几种?举例说明
【微信小程序】NFC 标签打开小程序
epoll + 线程池 + 前后置服务器分离
虚拟机vmware设置nat模式上网
余弦距离介绍
Cobalt Strike (CS) 逆向初探
flex布局
FreeRTOS中级篇
pytest接口自动化测试框架 | 基于Pytest的Web UI自动化测试框架介绍
力扣刷题之求两数之和
【C语言学习笔记(七)】C语言重定向输入与输出
LeetCode 952. Calculate Maximum Component Size by Common Factor
LeetCode 622. 设计循环队列
Interview Blitz: What Are Sticky Packs and Half Packs?How to deal with it?
面试突击:什么是粘包和半包?怎么解决?
ctfshow php features
The effective square of the test (one question of the day 7/29)
Teach you to locate online MySQL slow query problem hand by hand, package teaching package meeting
阿里巴巴政委体系-第七章、阿里政委培育
Unity gets the actual coordinates of the ui on the screen under the canvas