当前位置:网站首页>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;
}
边栏推荐
- A sharp tool for exposing data inconsistencies -- a real-time verification system
- How to Visualize Missing Data in R using a Heatmap
- Summary of flutter problems
- MySQL stored procedure cursor traversal result set
- This article takes you to understand the operation of vim
- php 根据经纬度查询距离
- Fabric. JS 3 APIs to set canvas width and height
- 【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
- Cluster Analysis in R Simplified and Enhanced
- 6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用
猜你喜欢
文件操作(详解!)
自然语言处理系列(三)——LSTM
Power Spectral Density Estimates Using FFT---MATLAB
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
K-Means Clustering Visualization in R: Step By Step Guide
【2022 ACTF-wp】
PyTorch搭建LSTM实现服装分类(FashionMNIST)
Cluster Analysis in R Simplified and Enhanced
HOW TO ADD P-VALUES TO GGPLOT FACETS
Pytorch builds LSTM to realize clothing classification (fashionmnist)
随机推荐
[visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
Cluster Analysis in R Simplified and Enhanced
How to Create a Nice Box and Whisker Plot in R
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
How does Premiere (PR) import the preset mogrt template?
文件操作(详解!)
Seriation in R: How to Optimally Order Objects in a Data Matrice
File operation (detailed!)
Uniapp uni list item @click, uniapp uni list item jump with parameters
ESP32 Arduino 引入LVGL 碰到的一些问题
HR wonderful dividing line
Deep understanding of NN in pytorch Embedding
The selected cells in Excel form have the selection effect of cross shading
Time format display
R HISTOGRAM EXAMPLE QUICK REFERENCE
Log4j2
This article takes you to understand the operation of vim
SVO2系列之深度濾波DepthFilter
基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)
Depth filter of SvO2 series