import java.util.Deque;
import java.util.LinkedList;
public class WindowTest {
public static void main(String[] args) {
int[] arr = {4,3,5,4,3,3,6,7};
WindowTest windowTest = new WindowTest();
int[] res = windowTest.getMaxByWindow(arr, 3);
for (int i = 0; i < res.length; i++) {
System.out.printf(res[i]+" ");
}
}
public int[] getMaxByWindow(int[] arr, int w){
if(arr == null || w < 1 || arr.length < w){
return null;
}
// 存放的是位置
LinkedList<Integer> qmax = new LinkedList<>();
int[] res = new int[arr.length-w+1];
int index = 0;
for (int i = 0; i < arr.length; i++) {
while(!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[i]){
qmax.pollLast();
}
qmax.addLast(i);
// 左窗口位置向右移动,那么就要判断队列中的最大数的位置要不要弹出队列
// i-w位置不在窗口里,那么i-w如果是最大数,也要弹出对立
if(qmax.peekFirst() == i-w){
qmax.pollFirst();
}
if(i >= w-1){
res[index++] = arr[qmax.peekFirst()];
}
}
return res;
}
}