Skip to content

Commit dbf19a9

Browse files
authored
Update 239.sliding-window-maximum.md
1 parent 091eab9 commit dbf19a9

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

problems/239.sliding-window-maximum.md

+8-12
Original file line numberDiff line numberDiff line change
@@ -162,18 +162,14 @@ Python3:
162162
```python
163163
class Solution:
164164
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
165-
deque, res, n = collections.deque(), [], len(nums)
166-
for i in range(n):
167-
# 移除前面实现的元素,整因为如此,才需要双端队列
168-
while deque and deque[0] < i - k + 1:
169-
deque.popleft()
170-
# 下面三行,类似单调递增栈
171-
while deque and nums[i] > nums[deque[-1]]:
172-
deque.pop()
173-
deque.append(i)
174-
if i >= k - 1:
175-
res.append(nums[deque[0]])
176-
return res
165+
q = collections.deque() # 本质就是单调队列
166+
ans = []
167+
for i in range(len(nums)):
168+
while q and nums[q[-1]] <= nums[i]: q.pop() # 维持单调性
169+
while q and i - q[0] >= k: q.popleft() # 移除失效元素
170+
q.append(i)
171+
if i >= k - 1: ans.append(nums[q[0]])
172+
return ans
177173
```
178174

179175
**复杂度分析**

0 commit comments

Comments
 (0)