題目:
給定一個數組和滑動窗口的大小,找出所有滑動窗口裏數值的最大值。例如,如果輸入數組{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.判斷當前最大值是否過期
2.新增加的值從隊尾開始比較,把所有比他小的值丟掉
代碼:
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
if (num == null || num.length == 0 || size <= 0 || num.length < size) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<>();
//雙端隊列,用來記錄每個窗口的最大值下標
LinkedList<Integer> qmax = new LinkedList<>();
for (int i = 0; i < num.length; i++) {
while (!qmax.isEmpty() && num[qmax.peekLast()] < num[i]) {
qmax.pollLast();
}
qmax.addLast(i);
//判斷隊首元素是否過期
if (qmax.peekFirst() == i - size) {
qmax.pollFirst();
}
//向result列表中加入元素
if (i >= size - 1) {
result.add(num[qmax.peekFirst()]);
}
}
return result;
}
}