当前位置:网站首页>数组——209.长度最小的子数组
数组——209.长度最小的子数组
2022-07-23 19:17:00 【向着百万年薪努力的小赵】
1 题目描述
- 长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
2 题目示例
示例 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
3 题目提示
- 1 <= target <= 109
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 105
4 思路
滑动窗口
所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。
首先要思考 如果用一个for循环,那么应该表示 滑动窗口的起始位置,还是终止位置。
如果只用一个for循环来表示 滑动窗口的起始位置,那么如何遍历剩下的终止位置?
解题的关键在于 窗口的起始位置如何移动
滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)暴力解法降为O(n)
所以,这个循环的索引,一定是表示 滑动窗口的终止位置。
5 我的答案
class Solution {
// 滑动窗口
public int minSubArrayLen(int s, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= s) {
result = Math.min(result, right - left + 1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
边栏推荐
- What if redis breaks down?
- 梅科尔工作室-华为14天鸿蒙设备开发实战笔记六
- Attack and defense world web question Fakebook
- Drools(1):Drools简介
- Set asp Net MVC site default page is the specified page
- 能量原理与变分法笔记14:总结+问题的求解
- QT With OpenGL(帧缓存篇)
- 2022山东养老展,中国国际养老服务业展览会,济南老龄产业展
- Energy principle and variational method note 17: generalized variational principle (identification factor method)
- 能量原理与变分法笔记19:最小余能原理+可能功原理
猜你喜欢
随机推荐
Mecol Studio - Little Bear Development Notes 3
What antenna is used for ant interface_ There is an interface at the back of the TV that says standard ant 75 Euro input. What does it mean, antenna? Can you connect the closed route "Suggested collec
新品上市|A股场内衍生品大盘点
Chinese [easy to understand] cannot be set when installing SVN localization package
absl教程(四):Strings Library
千呼万唤,5G双卡双通到底有多重要?
2022 Shandong elderly care exhibition, China International elderly care service industry exhibition, Jinan elderly care industry exhibition
Leetcode - the nearest sum of three numbers
QT With OpenGL(帧缓存篇)
13. Roman to Integer罗马数字转整数
TASK03|回归
Leetcode 228. summary interval (yes, solved)
Leetcode 219. duplicate Element II exists (yes, resolved)
20.ref与props
JDK installation package and MySQL installation package sorting
2022/7/21 training summary
Home NAS server (3) | SSD cache acceleration mechanical hard disk
2022 the fourth China International elderly care service industry exhibition was held in Jinan on September 26
关于网段CIDR的笔记
我在代码里面故意留个漏洞,违法吗?









