算法原理
利用单调性,使用《同向指针》来优化
其实这种滑动窗口的题本质上还是用指针来写的。
主要注意几个歩奏:
- 1,进窗口
- 2,判断
- 3,更新结果(依据题意来改变他的位置)
- 4,出窗口
正确性:
他利用单调性,规避了很多没有必要的枚举行为,因此虽然他使用了两个循环,但是他的时间复杂度只有O(1)
暴力解法(超时)
class Solution {
//暴力解法:
public int minSubArrayLen(int target, int[] nums) {
int count=99999;
for(int i =0;i< nums.length;i++) {
int sum =0;
int right =i,left = i;
while(right<nums.length) {
sum+=nums[right];
if(sum>=target) {
count = Math.min(count, right - left + 1);
break;
}
right++;
}
}
return count == 99999 ? 0:count;
}
}
滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n =nums.length,left =0,right =0,sum =0,count =Integer.MAX_VALUE;
while(right < n){
sum+=nums[right];//进窗口
while(sum>=target){//判断
count= Math.min(count,right - left +1);//更新结果
sum-=nums[left++];//出窗口
}
right++;
}
return count == Integer.MAX_VALUE ? 0:count;
}
}