public int minSubArrayLen(int target, int[] nums) {
//滑动窗口:计算每个位置可以得到的最小窗口的长度,但是时间复杂度太高
int left = 0;
int right = 0;
int sum = nums[0];
int len = nums.length + 1;
boolean isCan = true;
while (left < nums.length){
//计算当前位置最小窗口的长度
while (sum < target){
//扩大窗口
right++;
if (right < nums.length) {
sum += nums[right];
isCan = true;
}else {
//当前位置没有可以的
isCan = false;
break;
}
}
//计算len,移动到下一个位置
if (isCan){
len = Math.min(len,right-left+1);
}
left++;
right = left;
if (left < nums.length)
sum = nums[left];
}
return len == nums.length + 1 ? 0:len;
}
题解提醒
public int minSubArrayLen(int target, int[] nums) {
//滑动窗口,记录窗口和,然后计算是否可以缩小窗口
int left = 0,right = 0,res = Integer.MAX_VALUE,len = 0;
int sum = 0;
while (right < nums.length){
sum += nums[right];
right++;
while (sum >= target){
//查看是否能够缩小窗口,以及向右移动
len = right - left;//现在的长度
res = Math.min(len ,res);
sum -= nums[left];//先减小,然后计算长度
left++;
}
}
return res == Integer.MAX_VALUE?0:res;
}