File tree Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -299,7 +299,7 @@ class Solution {
299
299
```
300
300
301
301
### Python:
302
-
302
+ #### 解法一:使用自定义的单调队列类
303
303
``` python
304
304
from collections import deque
305
305
@@ -339,6 +339,36 @@ class Solution:
339
339
return result
340
340
```
341
341
342
+ #### 解法二:直接用单调队列
343
+ ``` python
344
+ from collections import deque
345
+
346
+
347
+ class Solution :
348
+ def maxSlidingWindow (self , nums : List[int ], k : int ) -> List[int ]:
349
+ max_list = [] # 结果集合
350
+ kept_nums = deque() # 单调队列
351
+
352
+ for i in range (len (nums)):
353
+ update_kept_nums(kept_nums, nums[i]) # 右侧新元素加入
354
+
355
+ if i >= k and nums[i - k] == kept_nums[0 ]: # 左侧旧元素如果等于单调队列头元素,需要移除头元素
356
+ kept_nums.popleft()
357
+
358
+ if i >= k - 1 :
359
+ max_list.append(kept_nums[0 ])
360
+
361
+ return max_list
362
+
363
+
364
+ def update_kept_nums (kept_nums , num ): # num 是新加入的元素
365
+ # 所有小于新元素的队列尾部元素,在新元素出现后,都是没有价值的,都需要被移除
366
+ while kept_nums and num > kept_nums[- 1 ]:
367
+ kept_nums.pop()
368
+
369
+ kept_nums.append(num)
370
+ ```
371
+
342
372
### Go:
343
373
344
374
``` go
You can’t perform that action at this time.
0 commit comments