239. Sliding Window Maximum
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
int[] result = new int[len - k + 1];
if(nums.length == 0) return new int[0];
Queue<Integer> queue = new PriorityQueue<Integer>((n1, n2) -> n2 - n1);
int i = 0;
for(; i < k; i ++) queue.add(nums[i]);
result[i - k] = queue.peek();
for(; i < len; i ++){
queue.remove(nums[i - k]);
queue.add(nums[i]);
result[i - k + 1] = queue.peek();
}
return result;
}
}Last updated
Was this helpful?