From 2aa31ce54bcb186376a1341d8ef91282a8db4c6f Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 21:42:07 +0800 Subject: [PATCH] =?UTF-8?q?0239.=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92?= =?UTF-8?q?=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 36 +++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index d9788f63..d7a94b5a 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -45,7 +45,7 @@ 这个队列应该长这个样子: -``` +```cpp class MyQueue { public: void pop(int value) { @@ -525,5 +525,39 @@ class Solution { } ``` +Swift解法二: + +```swift +func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] { + var result = [Int]() + var window = [Int]() + var right = 0, left = right - k + 1 + + while right < nums.count { + let value = nums[right] + + // 因为窗口移动丢弃的左边数 + if left > 0, left - 1 == window.first { + window.removeFirst() + } + + // 保证末尾的是最大的 + while !window.isEmpty, value > nums[window.last!] { + window.removeLast() + } + window.append(right) + + if left >= 0 { // 窗口形成 + result.append(nums[window.first!]) + } + + right += 1 + left += 1 + } + + return result +} +``` + -----------------------