给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{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]}。
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
if (num == null || size < 1 || num.length < size) {
return new ArrayList<Integer>();
}
ArrayList<Integer> res = new ArrayList<Integer>();
LinkedList<Integer> queue = new LinkedList<>();
for (int i = 0; i < num.length; i++) {
// 双端队列尾部的值 是否是小于等于这个值的
while (!queue.isEmpty() && num[queue.peekLast()] <= num[i]) {
queue.pollLast();
}
queue.addLast(i);
// 如果这个值过期了
if (queue.peekFirst() == i - size) {
queue.pollFirst();
}
// 依次放进去
if (i >= size - 1) {
res.add(num[queue.peekFirst()]);
}
}
return res;
}
}