滑动窗口(Sliding Window):
滑动窗口是一种用于处理数组或字符串中连续子序列的技巧。它通常用于解决涉及子数组或子字符串的问题,例如求取最长/最短的连续子序列,子序列满足某些条件等。基本思想是维护一个窗口,通过调整窗口的起始和结束位置,来找到满足特定条件的子序列。
具体步骤:
- 定义一个窗口的起始和结束位置。
- 通过移动窗口的起始或结束位置来调整窗口的大小。
- 在窗口大小满足特定条件时,进行相应的操作。
例题:
右边一直向前,左边根据情况判断是否向前(使用while简化过程)
c++代码:
class Solution {
public int longestSubarray(int[] nums) {
int n = nums.length, res = 0, cnt = 0;
for (int i = 0, j = 0; i < n; i++) {
if (nums[i] == 0) cnt++;
while (cnt > 1) {
if (nums[j++] == 0) cnt--;
}
res = Math.max(res, i - j);
}
return res;
}
}
java代码
class Solution {
public int longestSubarray(int[] nums) {
if(nums.length==1) return 0;
int res=0;//保存结果
//定义循环不变量[left..right] :区间 0 的个数不超过1
int left=0,right=0;
int count=0;//记录窗口内0的个数
while(right<nums.length){
if(nums[right]==0) ++count;
while(count>1){//0的个数超过1,收缩左窗口
if(nums[left]==0) --count;
++left;
}
res=Math.max(res,right-left);//删之前窗口内元素个数right-left+1,再删掉一个元素
++right;
}
return res;
}
}