239. Sliding Window Maximum [Hard]

/**
 * monotonic queue
 */
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int[] res = new int[nums.length - k + 1];
        LinkedList<Integer> queue = new LinkedList<>(); // to sotre and update the index of possible max value in the current window
        for (int i = 0; i < nums.length; i++) {
            while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) {
                queue.pollLast();
            }
            while (!queue.isEmpty() && queue.peek() <= i - k) {
                queue.poll();
            }
            queue.offer(i);
            if (i >= k - 1) {
                res[i - k + 1] = nums[queue.peek()];
            }
        }
        return res;
    }
}
上一篇:239. 滑动窗口最大值(Hard)


下一篇:239. 滑动窗口最大值