LeetCode 239. 滑动窗口最大值

Posted by cody1991 on August 9, 2020

简单思路:在窗口内每次设法把最大的数放在第一位,取出来用就可以了

239. 滑动窗口最大值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function (nums, k) {
  const queue = [];
  const result = [];

  for (let i = 0; i < nums.length; i++) {
    const cur = nums[i];

    if (queue.length === k) {
      queue.shift();

      while (queue[0] < Math.max(...queue)) {
        queue.shift();
      }
    }

    while (queue[0] < cur) {
      queue.shift();
    }

    queue.push(cur);

    if (i >= k - 1) {
      result.push(queue[0]);
    }
  }

  return result;
};

const nums = [1, 3, 1, 2, 0, 5],
  k = 3;

console.log(maxSlidingWindow(nums, k));