- 单调队列
[1]维护一个队列满足以下条件:队列单调递减
a.que.pop(滑动窗口移除的元素) 删除的值如果和出口值相同,则弹出元素,否则不做处理
b.que.push(滑动窗口添加的元素) 如果添加的元素比入口元素大,则弹出入口元素直到添加元素<=入口元素
c.que.front()返回我们想要的最大值
[2]首先将k个元素都push到单调队列中
[3]获取第一个最大值
[4]移动窗口,遍历后面的元素
a.pop(左边的元素)
b.push(右边的元素)
c.取出最大值放在result中 ```javascript class MyQueue { constructor() {
} push(value) {//整个队列是单调递减的this.que = [];
} pop(value) {while (this.que.length && value > this.que.slice(-1)) { this.que.pop(); } this.que.push(value);
} front() {if (this.que.length && value == this.front()) { this.que.shift(); }
} } var maxSlidingWindow = function (nums, k) { let result = []; let que = new MyQueue(); for (let i = 0; i < k; i++) {return this.que[0];
} result.push(que.front()); for (let i = k; i < nums.length; i++) {que.push(nums[i]);
} return result; }//移除左边的 que.pop(nums[i-k]); //添加右边的 que.push(nums[i]); //记录最大的 result.push(que.front());
const nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3; console.log(maxSlidingWindow(nums, k)); ```
