算法-双向队列

 1 public class MaxWindow {
 2     public int[] getMaxWindow(int[] arr, int w) {
 3         int[] res = new int[arr.length - w + 1];
 4         LinkedList<Integer> queue = new LinkedList<>();
 5         int index = 0;
 6         for (int i = 0; i < arr.length; i++) {
 7             while (!queue.isEmpty() && arr[queue.peekLast()] <= arr[i]) {
 8                 queue.pollLast();
 9             }
10             queue.offerLast(i);
11 
12             if (queue.peekFirst() == i - w) {
13                 queue.pollFirst();
14             }
15             if (i >= w - 1) {
16                 res[index++] = arr[queue.peekFirst()];
17             }
18 
19         }
20         return res;
21     }
22 }

双向队列找出滑动窗口中最大的值

新值从队尾插入,弹出队尾小于等于插入值的数

出窗口的数如果是队列头部最大值就弹出

posted @ 2021-07-26 15:58  rudynan  阅读(67)  评论(0编辑  收藏  举报