import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param num int整型一维数组 * @param size int整型 * @return int整型ArrayList */ public ArrayList<Integer> maxInWindows (int[] num, int size) { // write code here if(num.length == 0 || size > num.length || size == 0){ return new ArrayList<Integer>(); } ArrayList<Integer> ans = new ArrayList<>(num.length-size+1); PriorityQueue<int[]> pq = new PriorityQueue<>((arr1, arr2) -> arr1[0] != arr2[0] ? arr2[0] - arr1[0] : arr2[1] - arr1[1] ); for(int i = 0; i < size; i++){ pq.offer(new int[]{num[i], i}); } ans.add(pq.peek()[0]); for(int i = size; i < num.length; i++){ pq.offer(new int[]{num[i], i}); while(pq.peek()[1] <= i-size){ pq.poll(); } ans.add(pq.peek()[0]); } return ans; } }
使用优先队列,维护最大值,当最大值不在窗口内时出队