From 1516dc3d152b818f1e3d4f3675924c35918e0558 Mon Sep 17 00:00:00 2001 From: resyon Date: Sun, 30 May 2021 21:27:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=860239-golang=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 | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 6cc355ca..ed17157a 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -267,6 +267,36 @@ Python: Go: +```go +func maxSlidingWindow(nums []int, k int) []int { + var queue []int + var rtn []int + + for f := 0; f < len(nums); f++ { + //维持队列递减, 将 k 插入合适的位置, queue中 <=k 的 元素都不可能是窗口中的最大值, 直接弹出 + for len(queue) > 0 && nums[f] > nums[queue[len(queue)-1]] { + queue = queue[:len(queue)-1] + } + // 等大的后来者也应入队 + if len(queue) == 0 || nums[f] <= nums[queue[len(queue)-1]] { + queue = append(queue, f) + } + + if f >= k - 1 { + rtn = append(rtn, nums[queue[0]]) + //弹出离开窗口的队首 + if f - k + 1 == queue[0] { + queue = queue[1:] + } + } + } + + return rtn + +} + +``` + Javascript: ```javascript var maxSlidingWindow = function (nums, k) {