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 +} +``` + -----------------------