当前位置:网站首页>力扣209-长度最小的字符串——滑动窗口法
力扣209-长度最小的字符串——滑动窗口法
2022-08-02 11:41:00 【张怼怼√】
题目描述
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
解题思路

- 卡哥生动的滑动窗口法题解;
- 首先创建两个指针first 和 last 指向nums的 首部;
- 移动右指针,每移动一次考虑 first------last之间的值是否满足 >= target 的条件;
- 如果不满足,则 last 继续向右移动;
- 如果满足,则 first 指针向右移动;
- 统计每次满足条件的 first-----last之间的元素的个数,记录最小值,返回最小值。
- 在返回的时候应当加上判断条件看是否满足了sum条件,如果没有满足sum条件,最小值也没有更新,返回0.
输入输出示例

代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int len = nums.length;
int first = 0;
int sum = 0;
int min = Integer.MAX_VALUE;
for(int last = 0; last < len; last++){
sum += nums[last];
while(sum >= target){
min = Math.min(min,last-first+1);
sum -= nums[first++];
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}边栏推荐
猜你喜欢
随机推荐
JSP中include指令的功能简介说明
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
Failed to configure mysql, what's going on?
Coroutines and Lifecycle in Kotlin
X86函数调用模型分析
Create an application operation process using the kubesphere GUI
从幻核疑似裁撤看如何保证NFT的安全
解决anaconda下载pytorch速度极慢的方法
Camera Hal OEM模块 ---- cmr_snapshot.c
go语言的接口
MySQL主从复制几个重要的启动选项
【kali-信息收集】(1.8)ARP侦查工具_Netdiscover
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
企业级数据治理工作怎么开展?Datahub这样做
leetcode: 200. Number of islands
QT笔记——Q_PROPERTY了解
List排序 ,取最大值最小值
ECCV22|PromptDet:无需手动标注,迈向开放词汇的目标检测








