From a12ad31f46c082f35a88441d65ef322740d12520 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 16:03:36 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=880239.=E6=BB=91?= =?UTF-8?q?=E5=8A=A8=E7=AA=97=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E8=A7=84=E8=8C=83=E5=8C=96js=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 57 ++++++++++++++++++-------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 6e8039f4..adf3548c 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -395,26 +395,49 @@ func maxSlidingWindow(nums []int, k int) []int { Javascript: ```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ var maxSlidingWindow = function (nums, k) { - // 队列数组(存放的是元素下标,为了取值方便) - const q = []; - // 结果数组 - const ans = []; - for (let i = 0; i < nums.length; i++) { - // 若队列不为空,且当前元素大于等于队尾所存下标的元素,则弹出队尾 - while (q.length && nums[i] >= nums[q[q.length - 1]]) { - q.pop(); + class MonoQueue { + queue; + constructor() { + this.queue = []; + } + enqueue(value) { + let back = this.queue[this.queue.length - 1]; + 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]; + } } - // 入队当前元素下标 - q.push(i); - // 判断当前最大值(即队首元素)是否在窗口中,若不在便将其出队 - if (q[0] <= i - k) { - q.shift(); + let helperQueue = new MonoQueue(); + let i = 0, j = 0; + let resArr = []; + while (j < k) { + helperQueue.enqueue(nums[j++]); } - // 当达到窗口大小时便开始向结果中添加数据 - if (i >= k - 1) ans.push(nums[q[0]]); - } - return ans; + resArr.push(helperQueue.front()); + while (j < nums.length) { + helperQueue.enqueue(nums[j]); + helperQueue.dequeue(nums[i]); + resArr.push(helperQueue.front()); + i++, j++; + } + return resArr; }; ```