1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int[] ans = new int[nums.length - k + 1]; Queue<int[]> queue = new PriorityQueue<int[]>((o1, o2)->{ if(o2[0] - o1[0] > 0){ return 1; }else if(o2[0] - o1[0] < 0){ return -1; }else{ if(o2[1] - o1[1] >= 0){ return 1; }else{ return -1; } } });
for(int i = 0; i < k; i++){ queue.offer(new int[]{nums[i], i}); }
ans[0] = queue.peek()[0];
for(int i = k; i < nums.length; i++){ while(!queue.isEmpty() && queue.peek()[1] < (i - k + 1)){ queue.poll(); } queue.offer(new int[]{nums[i], i}); ans[i-k+1] = queue.peek()[0]; } return ans; } }
|