【路飞】239. 滑动窗口最大值

422 阅读2分钟

题目描述

239. 滑动窗口最大值

难度 困难

给你一个整数数组 nums,有一个大小为 k **的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值 。   示例 1:

输入: nums = [1,3,-1,-3,5,3,6,7], k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[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

示例 2:

输入: nums = [1], k = 1
输出: [1]

 

提示:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 1 <= k <= nums.length

解析

  1. 创建一个临时的栈(stack)保存当前窗口的值;
  2. 每次计算stack里面的最大值,并保存到结果里面;
function maxSlidingWindow(nums, k) {
  const stack = [];
  const res = [];
  const len = nums.length;
  for(let i = 0; i < len; i++) {
    //先把窗口的前 k - 1 填满
    if(i < k - 1) {
      stack.push(nums[i]);
    } else {
      stack.push(nums[i]);
      res.push(Math.max(...stack));
      stack.shift()
    }
  }
  return res;
}

写完收工✌️,结果一提交发现不通过,力扣给出了一个超级大的数组,下图数组只截取了一小部分:

image.png

分析问题

  1. 在计算max的时候以及shift的时候,花销较大;
  2. 优化方式:减少当前维护的stack长度,这里使用单调队列:队列中的元素全都是单调递增(或递减)的
class MonotonicQueue {
  queue = [];
  push(n) {
    // queue里面最多只维护两个值
    while (this.queue.length && this.queue[this.queue.length - 1] < n) {
      this.queue.pop();
    }
    this.queue.push(n);
  }
  pop(n) {
    // 当要移除的值和当前最大值相等时才移除,因为比它小的值在push时就被移除了
    if (n === this.max) {
      this.queue.shift();
    }
  }
  get max() {
    return this.queue[0];
  }
}

function maxSlidingWindow(nums, k) {
  const queue = new MonotonicQueue();
  const res = [];
  const len = nums.length;
  for (let i = 0; i < len; i++) {
    if (i < k - 1) {
      queue.push(nums[i]);
    } else {
      queue.push(nums[i]);
      res.push(queue.max);
      queue.pop(nums[i - k + 1]);
    }
  }
  return res;
}

再次跑一下测试:

image.png