algorithm-base/animation-simulation/数组篇/长度最小的子数组.md

127 lines
4.2 KiB
Java
Raw Normal View History

2021-03-21 04:10:31 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [209. ](https://leetcode-cn.com/problems/minimum-size-subarray-sum/)
####
> n s s 0
> s = 7, nums = [2,3,1,2,4,3]
> 2
> [4,3]
####
****
2021-03-21 05:18:59 +00:00
![](https://img-blog.csdnimg.cn/20210321131617533.png)
2021-03-21 04:10:31 +00:00
![](https://img-blog.csdnimg.cn/2021032111513777.gif)
####
Java Code:
2021-03-21 04:10:31 +00:00
```java
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int len = nums.length;
int windowlen = Integer.MAX_VALUE;
int i = 0;
int sum = 0;
for (int j = 0; j < len; ++j) {
sum += nums[j];
while (sum >= s) {
windowlen = Math.min (windowlen, j - i + 1);
sum -= nums[i];
i++;
}
}
return windowlen == Integer.MAX_VALUE ? 0 : windowlen;
}
}
```
C++ Code:
```cpp
class Solution {
public:
int minSubArrayLen(int t, vector<int>& nums) {
int n = nums.size();
int i = 0, sum = 0, winlen = INT_MAX;
for(int j = 0; j < n; ++j){
sum += nums[j];
while(sum >= t){
winlen = min(winlen, j - i + 1);
sum -= nums[i++];
}
}
return winlen == INT_MAX? 0: winlen;
}
};
```
Python3 Code:
```python
from typing import List
import sys
class Solution:
def minSubArrayLen(self, s: int, nums: List[int])->int:
leng = len(nums)
windowlen = sys.maxsize
i = 0
sum = 0
for j in range(0, leng):
sum += nums[j]
while sum >= s:
windowlen = min(windowlen, j - i + 1)
sum -= nums[i]
i += 1
if windowlen == sys.maxsize:
return 0
else:
return windowlen
```
2021-07-17 04:13:15 +00:00
Swift Code
```swift
class Solution {
func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int {
var sum = 0, windowlen = Int.max, i = 0
for j in 0..<nums.count {
sum += nums[j]
while sum >= target {
windowlen = min(windowlen, j - i + 1)
sum -= nums[i]
i += 1
}
}
return windowlen == Int.max ? 0 : windowlen
}
}
```