修改(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++) { }
// 若队列不为空,且当前元素大于等于队尾所存下标的元素,则弹出队尾 enqueue(value) {
while (q.length && nums[i] >= nums[q[q.length - 1]]) { let back = this.queue[this.queue.length - 1];
q.pop(); while (back !== undefined && back < value) {
this.queue.pop();
back = this.queue[this.queue.length - 1];
}
this.queue.push(value);
}
dequeue(value) {
let front = this.front();
if (front === value) {
this.queue.shift();
}
}
front() {
return this.queue[0];
}
} }
// 入队当前元素下标 let helperQueue = new MonoQueue();
q.push(i); let i = 0, j = 0;
// 判断当前最大值(即队首元素)是否在窗口中,若不在便将其出队 let resArr = [];
if (q[0] <= i - k) { while (j < k) {
q.shift(); helperQueue.enqueue(nums[j++]);
} }
// 当达到窗口大小时便开始向结果中添加数据 resArr.push(helperQueue.front());
if (i >= k - 1) ans.push(nums[q[0]]); while (j < nums.length) {
} helperQueue.enqueue(nums[j]);
return ans; helperQueue.dequeue(nums[i]);
resArr.push(helperQueue.front());
i++, j++;
}
return resArr;
}; };
``` ```