《挑战程序设计竞赛》这本书中把滑动窗口叫做「虫取法」,我觉得非常生动形象。因为滑动窗口的两个指针移动的过程和虫子爬动的过程非常像:前脚不动,把后脚移动过来;后脚不动,把前脚向前移动。
我分享一个滑动窗口的模板,能解决大多数的滑动窗口问题
def findSubArray(nums):
N = len(nums) # 数组/字符串长度
left, right = 0, 0 # 双指针,表示当前遍历的区间[left, right],闭区间
sums = 0 # 用于统计 子数组/子区间 是否有效,根据题目可能会改成求和/计数
res = 0 # 保存最大的满足题目要求的 子数组/子串 长度
while right < N: # 当右边的指针没有搜索到 数组/字符串 的结尾
sums += nums[right] # 增加当前右边指针的数字/字符的求和/计数
while 区间[left, right]不符合题意:# 此时需要一直移动左指针,直至找到一个符合题意的区间
sums -= nums[left] # 移动左指针前需要从counter中减少left位置字符的求和/计数
left += 1 # 真正的移动左指针,注意不能跟上面一行代码写反
# 到 while 结束时,我们找到了一个符合题意要求的 子数组/子串
res = max(res, right - left + 1) # 需要更新结果
right += 1 # 移动右指针,去探索新的区间
return res
滑动窗口中用到了左右两个指针,它们移动的思路是:以右指针作为驱动,拖着左指针向前走。右指针每次只移动一步,而左指针在内部 while 循环中每次可能移动多步。右指针是主动前移,探索未知的新区域;左指针是被迫移动,负责寻找满足题意的区间。
模板的整体思想是:
另外一个需要根据题目去修改的是内层 while 循环的判断条件,即: 区间 **[left, right]**不符合题意 。对于本题而言,就是该区间内的 0 的个数 超过了 2 。
以上引用自负雪明烛的算法模板
class Solution {
public int longestSubarray(int[] nums, int limit) {
int len = nums.length;
int l = 0, r = 0;
int ret = 0;
PriorityQueue<Integer> minQueue = new PriorityQueue<>((o1, o2) -> o1-o2);
PriorityQueue<Integer> maxQueue = new PriorityQueue<>((o1, o2) -> o2-o1);
while (r < len && l < len) {
minQueue.add(nums[r]);
maxQueue.add(nums[r]);
while (r < len && maxQueue.peek()-minQueue.peek() > limit) {
minQueue.remove(nums[l]);
maxQueue.remove(nums[l]);
l++;
}
ret = Math.max(ret, r-l+1);
r++;
}
return ret;
}
}
总结:
// 方法一
PriorityQueue<Integer> minQueue = new PriorityQueue<>((o1, o2) -> o1-o2);
PriorityQueue<Integer> maxQueue = new PriorityQueue<>((o1, o2) -> o2-o1);
// 方法二
PriorityQueue<Integer> minQueue = new PriorityQueue<>(Comparator.naturalOrder());
PriorityQueue<Integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder());
class Solution {
public int longestSubarray(int[] nums, int limit) {
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
int n = nums.length;
int left = 0, right = 0;
int ret = 0;
while (right < n) {
map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);
while (map.lastKey() - map.firstKey() > limit) {
map.put(nums[left], map.get(nums[left]) - 1);
if (map.get(nums[left]) == 0) {
map.remove(nums[left]);
}
left++;
}
ret = Math.max(ret, right - left + 1);
right++;
}
return ret;
}
}