Leecode 0239. Sliding Window Maximum
239. Sliding Window Maximum
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
1 | Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 |
Example 2:
1 | Input: nums = [1], k = 1 |
题目大意
给定一个整数数组 nums
和一个大小为 k
的滑动窗口,该窗口从数组的最左侧移动到最右侧。每次窗口向右移动一个位置,返回窗口中的最大值。
例如,对于数组 [1,3,-1,-3,5,3,6,7]
和 k=3
,滑动窗口的最大值序列为 [3,3,5,5,6,7]
。
解题思路
解决滑动窗口最大值的高效方法是使用单调队列(Monotonic Queue),核心思路是维护一个队列,使其始终保持递减顺序,队首元素即为当前窗口的最大值。具体步骤如下:
- 初始化单调队列:队列存储数组元素的索引(而非值),确保队列中的元素对应的值是递减的。
- 处理前
k
个元素:- 对于每个元素,移除队列中所有小于当前元素的元素(它们不可能成为窗口最大值)。
- 将当前元素的索引加入队列。
- 滑动窗口移动:
- 移除队列中超出当前窗口范围的元素(索引 ≤ 当前索引 -
k
)。 - 对新加入窗口的元素,重复步骤 2 的移除操作。
- 将当前队列的队首元素(最大值)加入结果集。
- 移除队列中超出当前窗口范围的元素(索引 ≤ 当前索引 -
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.