0239. Sliding Window Maximum (H)

Sliding Window Maximum (H)

题目

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

Return the max sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation: 
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]      7

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:

Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:

Input: nums = [9,11], k = 2
Output: [11]

Example 5:

Input: nums = [4,-2], k = 2
Output: [4]

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

题意

给定一个数组和一个定长窗口,将窗口在数组上从左到右滑动,记录每一步在当前窗口中的最大值。

思路

  1. 优先队列

    维护一个优先队列,存储一个数值对(nums[index], index)。遍历数组,计算当前窗口的左边界left,将当前数字加入到优先队列中,查看当前优先队列中的最大值的下标是否小于left,如果是则说明该最大值不在当前窗口中,出队,重复操作直到最大值在当前窗口中,并加入结果集。

  2. 双向队列

    维护一个双向队列,存储下标。遍历数组,计算当前窗口的左边界left,如果队首元素小于left则出队;接着从队尾开始,将所有小于当前元素的下标依次出队,最后将当前下标入队。这样能保证每次剩下的队首元素都是当前窗口中的最大值。


代码实现

Java

优先队列

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int[] ans = new int[nums.length - k + 1];
        Queue<int[]> q = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        int left = 0;

        for (int i = 0; i < nums.length; i++) {
            left = i - k + 1;
            q.offer(new int[]{nums[i], i});

            if (left >= 0) {
                while (q.peek()[1] < left) {
                    q.poll();
                }
                ans[left] = q.peek()[0];
            }
        }

        return ans;
    }
}

双向队列

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int[] ans = new int[nums.length - k + 1];
        Deque<Integer> q = new ArrayDeque<>();

        for (int i = 0; i < nums.length; i++) {
            int left = i - k + 1;

            if (!q.isEmpty() && q.peekFirst() < left) {
                q.pollFirst();
            }
            while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) {
                q.pollLast();
            }
            q.offerLast(i);

            if (left >= 0) {
                ans[left] = nums[q.peekFirst()];
            }
        }

        return ans;
    }
}
posted @ 2020-11-28 21:03  墨云黑  阅读(101)  评论(0编辑  收藏  举报