问题描述1
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
练习地址
实现1
public class C59_deque_MaxInWindows {
public static int[] getMaxWindow(int[] arr, int w) {
if (arr == null || w < 1 || arr.length < w) {
return null;
}
LinkedList<Integer> deque = new LinkedList<Integer>();
//长度为N-w+1 的数组
int[] res = new int[arr.length - w + 1];
int index = 0;
for (int i = 0; i < arr.length; i++) {
// 1 双端队列不为空,队尾小,从尾部删除所有,从而保证队列头尾最大值
while (!deque.isEmpty() && arr[deque.peekLast()] < arr[i]) {
deque.pollLast();
}
//2 添加arr[i]的下标到队尾
deque.addLast(i);
//3 队头过期,推出
if (deque.peekFirst() == i - w) {
deque.pollFirst();
}
if (i >= w - 1) {//队列到达滑动窗口大小,w=3,1,2的时候都不存在最大值
res[index++] = arr[deque.peekFirst()];
}
}
return res;
}
}
Test
public static void main(String[] args) {
int[] arr = {2, 3, 4, 2, 6, 2, 5, 1};
int[] res = getMaxWindow(arr, 3);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
问题描述2
请定义一个队列并实现函数max得到队列里的最大值,要求函数max,push_back和pop_front的实践复杂度为O(1)