Window Size: 3
Current Maximum:
1
3
-1
-3
5
3
6
7
Maximum Values Array:
Animation Speed:
Algorithm Implementation
def maxSlidingWindow(nums: List[int], k: int) -> List[int]:
result = []
if not nums or k == 0:
return result
# 使用双端队列存储索引
deque = collections.deque()
# 初始化第一个窗口
for i in range(k):
# 保持队列递减
while deque and nums[i] >= nums[deque[-1]]:
deque.pop()
deque.append(i)
# 将第一个窗口的最大值加入结果
result.append(nums[deque[0]])
# 处理剩余窗口
for i in range(k, len(nums)):
# 移除窗口外的元素
while deque and deque[0] <= i - k:
deque.popleft()
# 保持队列递减
while deque and nums[i] >= nums[deque[-1]]:
deque.pop()
deque.append(i)
result.append(nums[deque[0]])
return result