修改(0239.滑动窗口最大值.md):规范化js版本

This commit is contained in:
Steve2020
2022-01-24 16:03:36 +08:00
parent ac9f8c6120
commit a12ad31f46

View File

@ -395,26 +395,49 @@ func maxSlidingWindow(nums []int, k int) []int {
Javascript: Javascript:
```javascript ```javascript
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSlidingWindow = function (nums, k) { var maxSlidingWindow = function (nums, k) {
// 队列数组(存放的是元素下标,为了取值方便) class MonoQueue {
const q = []; queue;
// 结果数组 constructor() {
const ans = []; this.queue = [];
for (let i = 0; i < nums.length; i++) {
// 若队列不为空,且当前元素大于等于队尾所存下标的元素,则弹出队尾
while (q.length && nums[i] >= nums[q[q.length - 1]]) {
q.pop();
} }
// 入队当前元素下标 enqueue(value) {
q.push(i); let back = this.queue[this.queue.length - 1];
// 判断当前最大值(即队首元素)是否在窗口中,若不在便将其出队 while (back !== undefined && back < value) {
if (q[0] <= i - k) { this.queue.pop();
q.shift(); back = this.queue[this.queue.length - 1];
} }
// 当达到窗口大小时便开始向结果中添加数据 this.queue.push(value);
if (i >= k - 1) ans.push(nums[q[0]]);
} }
return ans; dequeue(value) {
let front = this.front();
if (front === value) {
this.queue.shift();
}
}
front() {
return this.queue[0];
}
}
let helperQueue = new MonoQueue();
let i = 0, j = 0;
let resArr = [];
while (j < k) {
helperQueue.enqueue(nums[j++]);
}
resArr.push(helperQueue.front());
while (j < nums.length) {
helperQueue.enqueue(nums[j]);
helperQueue.dequeue(nums[i]);
resArr.push(helperQueue.front());
i++, j++;
}
return resArr;
}; };
``` ```