题目

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:

  1. Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
  2. Output: [3,3,5,5,6,7]
  3. Explanation:
  4. Window position Max
  5. --------------- -----
  6. [1 3 -1] -3 5 3 6 7 3
  7. 1 [3 -1 -3] 5 3 6 7 3
  8. 1 3 [-1 -3 5] 3 6 7 5
  9. 1 3 -1 [-3 5 3] 6 7 5
  10. 1 3 -1 -3 [5 3 6] 7 6
  11. 1 3 -1 -3 5 [3 6 7] 7

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

  1. Input: nums = [4,-2], k = 2
  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

优先队列

  1. class Solution {
  2. public int[] maxSlidingWindow(int[] nums, int k) {
  3. int[] ans = new int[nums.length - k + 1];
  4. Queue<int[]> q = new PriorityQueue<>((a, b) -> b[0] - a[0]);
  5. int left = 0;
  6. for (int i = 0; i < nums.length; i++) {
  7. left = i - k + 1;
  8. q.offer(new int[]{nums[i], i});
  9. if (left >= 0) {
  10. while (q.peek()[1] < left) {
  11. q.poll();
  12. }
  13. ans[left] = q.peek()[0];
  14. }
  15. }
  16. return ans;
  17. }
  18. }

双向队列

  1. class Solution {
  2. public int[] maxSlidingWindow(int[] nums, int k) {
  3. int[] ans = new int[nums.length - k + 1];
  4. Deque<Integer> q = new ArrayDeque<>();
  5. for (int i = 0; i < nums.length; i++) {
  6. int left = i - k + 1;
  7. if (!q.isEmpty() && q.peekFirst() < left) {
  8. q.pollFirst();
  9. }
  10. while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) {
  11. q.pollLast();
  12. }
  13. q.offerLast(i);
  14. if (left >= 0) {
  15. ans[left] = nums[q.peekFirst()];
  16. }
  17. }
  18. return ans;
  19. }
  20. }