L R 3 2 4 6 0 17
L,R 只能往右滑动
L边界不能超过R边界的情况下,随便往右滑动。
L是出窗口,R是入窗口
双端队列结构: 维持头部最大值
R+1滑动进来的数比当前值大,就让当前数弹出,比当前值小就在后面待着。最大值一直都会是头位置的值。
L+1如果是头部位置从头弹出,如果过期的数不是头部位置就不管。
public static int[] maxSlidingWindow(int[] arr, int w) {
if (arr == null || w < 1 || arr.length < w) {
return null;
}
LinkedList<Integer> qmax = new LinkedList<Integer>();
int[] res = new int[arr.length - w + 1];
int index = 0;
for (int R = 0; R < arr.length; 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;
}