给定一个数组和滑动窗口的大小,找出全部滑动窗口里数值的最大值。例如,若是输入数组 {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; } }