Skip to content

Commit 8b59803

Browse files
committed
add LeetCode 209. 长度最小的子数组
1 parent 04e7535 commit 8b59803

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
7+
8+
9+
10+
示例:
11+
12+
```javascript
13+
输入:s = 7, nums = [2,3,1,2,4,3]
14+
输出:2
15+
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
16+
```
17+
18+
进阶:
19+
20+
- 如果你已经完成了 O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
21+
22+
来源:力扣(LeetCode)
23+
链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
24+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
25+
26+
## 解题思路
27+
28+
滑动窗口,利用双指针实现,从左到右看,满足条件就把左指针左移,找到最小的长度,然后每次窗口右指针都往右滑动,直到数组末尾。
29+
30+
```javascript
31+
/**
32+
* @param {number} s
33+
* @param {number[]} nums
34+
* @return {number}
35+
*/
36+
var minSubArrayLen = function (s, nums) {
37+
let len = nums.length;
38+
let L = 0, R = 0;
39+
let res = Infinity, sum = 0;
40+
while (R < len) {
41+
sum += nums[R];
42+
while (sum >= s) { // 滑动窗口
43+
res = Math.min(res, R - L + 1);
44+
sum -= nums[L];
45+
L++;
46+
}
47+
R++;
48+
}
49+
return res == Infinity ? 0 : res; // 判断合法性
50+
};
51+
```
52+
53+
54+
55+
## 最后
56+
文章产出不易,还望各位小伙伴们支持一波!
57+
58+
往期精选:
59+
60+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
61+
62+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
63+
64+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
65+
66+
67+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
68+
69+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
70+
71+
```javascript
72+
学如逆水行舟,不进则退
73+
```
74+
75+

0 commit comments

Comments
 (0)