题目
有一个整数型数组arr 和一个大小为w 的窗口从数组的最左边滑到最右边,窗口每次向右边滑一个位置。
例如:数组为[4,3,5,4,3,3,6,7] 数组长度为n 窗口大小w 则一共产生n-w+1 数组长度的数组。
解析
- 采用队列
- 集中思考:窗口在滑动过程中如果更快的完成查找最大值的过程
- 只要遍历该数组,同时在双端队列的头维护当前窗口的最大值,并将最大值放到数组中
- 注意下图双端队列放入的是具体的值,代码中采用下标(下图来自‘Google大神’)
题解
public class MaxWindow {
public static int[] getMaxWindow(int[] arr, int w) {
//边界限制
if (arr == null || w < 1 || arr.length < w) {
return new int[0];
}
//滑动窗口通过双向链表实现
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);
//保障窗口大小
if (qmax.peekFirst() == i - w) {
qmax.pollFirst();
}
//根据数组长度
if (i >= w - 1) {
res[index++] = arr[qmax.peekFirst()];
}
}
return res;
}
public static void main(String[] args) {
// int[] arr = {5,9,3,8,7};
int[] arr = {1, 3, -1, -3, 5, 3, 6, 7};
Arrays.stream(getMaxWindow(arr, 3)).forEach(System.out::print);
}
}