mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
0239.滑动窗口最大值:优化排版,补充Swift版本
This commit is contained in:
@ -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
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user