当前位置:网站首页>Leetcode209 长度最小的子数组
Leetcode209 长度最小的子数组
2022-07-02 09:42:00 【魑魅魍魉114】
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
滑动窗口:
定义两个指针 start 和end 分别表示子数组(滑动窗口窗口)的开始位置和结束位置,维护变量 sum 存储子数组中的元素和nums[start] 到nums[end] 的元素和。
初始状态下,start 和end 都指向下标 0,sum 的值为 0。
每一轮迭代,将 nums[end] 加到sum,如果sum≥s,则更新子数组的最小长度(此时子数组的长度是 end−start+1),然后将nums[start] 从sum 中减去并将start 右移,直到 sum<s,在此过程中同样更新子数组的最小长度。在每一轮迭代的最后,将end 右移。
public int minSubArrayLen(int target, int[] nums) {
int start = 0;
int len = Integer.MAX_VALUE;
int sum = 0;
for(int end = 0; end < nums.length; end++){
sum += nums[right];
while(sum >= target){
len = Math.min(len,end-start+1);
sum -= nums[start++];
}
}
return len == Integer.MAX_VALUE ? 0 : len;
}边栏推荐
- (C语言)八进制转换十进制
- ORB-SLAM2不同线程间的数据共享与传递
- Esp32 audio frame esp-adf add key peripheral process code tracking
- File operation (detailed!)
- K-Means Clustering Visualization in R: Step By Step Guide
- YYGH-BUG-05
- PyTorch搭建LSTM实现服装分类(FashionMNIST)
- Analyse de l'industrie
- PX4 Position_ Control RC_ Remoter import
- 深入理解P-R曲线、ROC与AUC
猜你喜欢

YYGH-BUG-05

Cluster Analysis in R Simplified and Enhanced

How to Create a Beautiful Plots in R with Summary Statistics Labels

2022年遭“挤爆”的三款透明LED显示屏

【2022 ACTF-wp】

K-Means Clustering Visualization in R: Step By Step Guide

自然语言处理系列(二)——使用RNN搭建字符级语言模型

How to Easily Create Barplots with Error Bars in R

数据分析 - matplotlib示例代码
![[geek challenge 2019] upload](/img/04/731323142161a4994c14fedae38b81.jpg)
[geek challenge 2019] upload
随机推荐
Implementation of address book (file version)
conda常用命令汇总
Data analysis - Matplotlib sample code
How to Visualize Missing Data in R using a Heatmap
uniapp uni-list-item @click,uniapp uni-list-item带参数跳转
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
The selected cells in Excel form have the selection effect of cross shading
Log4j2
Cluster Analysis in R Simplified and Enhanced
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
PyTorch中repeat、tile与repeat_interleave的区别
pgsql 字符串转数组关联其他表,匹配 拼接后原顺序展示
ESP32音频框架 ESP-ADF 添加按键外设流程代码跟踪
自然语言处理系列(三)——LSTM
How to Add P-Values onto Horizontal GGPLOTS
php 根据经纬度查询距离
Mish-撼动深度学习ReLU激活函数的新继任者
Pytorch builds LSTM to realize clothing classification (fashionmnist)
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
机械臂速成小指南(七):机械臂位姿的描述方法