# 算法 - 数组 - 滑动窗口

``````给定一个含有 n 个正整数的数组和一个正整数 target 。

## 暴力解法

``````class Solution {
public int minSubArrayLen(int target, int[] nums) {

int minLength = nums.length+1;

for(int left = 0;left < nums.length; left++){
for(int right = left; right< nums.length; right++){
int sum = 0;
for(int i = left; i <= right; i++){
sum += nums[i];
}
if(sum >= target){
int tmplength = right-left+1;
minLength = min(tmplength, minLength);
break;
}
}
}
if(minLength == nums.length+1){
return 0;
}
return minLength;
}

int min(int a, int b){
return a < b? a:b;
}
}``````

## 滑动窗口

``````class Solution {
public int minSubArrayLen(int target, int[] nums) {
int minLength = nums.length +1;
int left = 0;
int sum = 0;
for(int right = 0; right < nums.length; right++){
sum += nums[right];
while(sum >= target){
int l = right-left+1;
minLength = min(l, minLength);
sum -= nums[left++];
}
}
return minLength==nums.length +1? 0: minLength;
}

int min(int a, int b){
return a < b? a:b;
}
}``````

##### 刘博博客
Java、分布式微服务相关技术整理

Java架构师，技术经理

863 声望
45 粉丝
0 条评论