滑动窗口
思想
-
要解决的问题?
1.滑动窗口的最大值和最小值
2.题目链接:https://leetcode.cn/problems/sliding-window-maximum/description/
https://leetcode.cn/problems/gas-station/
还有个面值dp,学完动态规划再回来做
-
时间复杂度 O(N)
(暴力时间复杂度是O(N^3)
-
规定窗口
1.原则:L<=R
2.任何时刻,L++(数从右侧进窗口),R++(数从左侧进窗口)
-
更新结构
双端队列
板子
//返回滑动窗口最大值
public static int[] getMaxWindow(int[] arr,int w) {
if(arr == null || arr.length < w || w < 1) {
return null;
}
int N = arr.length;
int res[] = new int[N - w + 1];//答案数组
int index = 0; //答案的下标
LinkedList<Integer> qmax = new LinkedList<>();
for(int R = 0; R < N; R ++ ) {
//右边的要不要滚
while(!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[R])
qmax.pollLast();
qmax.addLast(R);
//左边的下标是否过期
if(qmax.peekFirst() == R - w) {
qmax.pollFirst();
}
//达到第一个窗口
if(R >= w - 1) {
res[index++] = arr[qmax.peekFirst()];
}
}
return res;
}