給定一個數組和滑動窗口的大小,找出全部滑動窗口裏數值的最大值。例如,若是輸入數組 {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]}。
窗口大於數組長度的時候,返回空java
最簡單的思路就是使用雙指針 + 優先級隊列數組
import java.util.PriorityQueue; import java.util.Comparator; import java.util.ArrayList; public class Solution { private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(3, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); public ArrayList<Integer> maxInWindows(int [] num, int size) { ArrayList<Integer> list = new ArrayList<>(); if(num.length == 0 || num.length < size) { return list; } int low = 0; int high = low + size - 1; while(high <= num.length - 1) { for(int i = low; i <= high; i++) { maxHeap.offer(num[i]); } Integer result = maxHeap.poll(); if(result != null) { list.add(result); } maxHeap.clear(); low++; high++; } return list; } }
第二種思路就是使用雙端隊列,遍歷數組,對於每個新加進來的元素,都先判斷是否比隊尾的元素大,這樣一來隊列頭保存的確定就是當前滑動窗口中最大的值了。在彈出隊頭元素時,還要判斷一下元素是否過時ide
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<>(); int index = 0; 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; } }