239. 滑动窗口最大值
题目描述
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 输出:[3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
示例 2:
输入:nums = [1], k = 1 输出:[1]
提示:
1 <= nums.length <= 105-104 <= nums[i] <= 1041 <= k <= nums.length
方法一:优先队列(大根堆)
我们可以使用优先队列(大根堆)来维护滑动窗口中的最大值。
先将前
时间复杂度
可视化演示
以
nums = [3, 1, 2, -1],k = 3为例,演示优先队列(大根堆):绿色为当前窗口,指针i标当前新入堆元素,指针堆顶标堆顶对应数组位置;黄色为本次涉及的元素。点击 ▶ 播放,或逐步操作。
30
11
22
-13
滑动窗口 [0, 1](绿色区域)
0非零交换中窗口内指针位置
初始化:把前 k-1=2 个元素入大根堆:(3,0)、(1,1)。堆顶为 (3,0),即 nums[0]=3
1 / 3
java
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
PriorityQueue<int[]> q
= new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
int n = nums.length;
for (int i = 0; i < k - 1; ++i) {
q.offer(new int[] {nums[i], i});
}
int[] ans = new int[n - k + 1];
for (int i = k - 1, j = 0; i < n; ++i) {
q.offer(new int[] {nums[i], i});
while (q.peek()[1] <= i - k) {
q.poll();
}
ans[j++] = q.peek()[0];
}
return ans;
}
}cpp
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
priority_queue<pair<int, int>> q;
int n = nums.size();
for (int i = 0; i < k - 1; ++i) {
q.push({nums[i], -i});
}
vector<int> ans;
for (int i = k - 1; i < n; ++i) {
q.push({nums[i], -i});
while (-q.top().second <= i - k) {
q.pop();
}
ans.emplace_back(q.top().first);
}
return ans;
}
};python
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = [(-v, i) for i, v in enumerate(nums[: k - 1])]
heapify(q)
ans = []
for i in range(k - 1, len(nums)):
heappush(q, (-nums[i], i))
while q[0][1] <= i - k:
heappop(q)
ans.append(-q[0][0])
return ans方法二:单调队列
这道题也可以使用单调队列来解决。时间复杂度
单调队列常见模型:找出滑动窗口中的最大值/最小值。模板:
python
q = deque()
for i in range(n):
# 判断队头是否滑出窗口
while q and checkout_out(q[0]):
q.popleft()
while q and check(q[-1]):
q.pop()
q.append(i)可视化演示
以
nums = [1, 3, -1, -3, 5, 3, 6, 7],k = 3为例,演示单调队列:绿色为当前窗口,指针队首/队尾指向单调递减队列q的首尾下标,指针i标当前元素;黄色为本次被弹出/入队的元素。点击 ▶ 播放,或逐步操作。
i▼
10
31
-12
-33
54
35
66
77
滑动窗口 [0, 0](绿色区域)
0非零交换中窗口内指针位置
i=0:q 为空,直接入队 → q=[0](存下标)。窗口未满(k=3),暂不记录最大值
1 / 8
java
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
int[] ans = new int[n - k + 1];
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0, j = 0; i < n; ++i) {
if (!q.isEmpty() && i - k + 1 > q.peekFirst()) {
q.pollFirst();
}
while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
q.pollLast();
}
q.offer(i);
if (i >= k - 1) {
ans[j++] = nums[q.peekFirst()];
}
}
return ans;
}
}cpp
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;
vector<int> ans;
for (int i = 0; i < nums.size(); ++i) {
if (!q.empty() && i - k + 1 > q.front()) {
q.pop_front();
}
while (!q.empty() && nums[q.back()] <= nums[i]) {
q.pop_back();
}
q.push_back(i);
if (i >= k - 1) {
ans.emplace_back(nums[q.front()]);
}
}
return ans;
}
};python
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = deque()
ans = []
for i, v in enumerate(nums):
if q and i - k + 1 > q[0]:
q.popleft()
while q and nums[q[-1]] <= v:
q.pop()
q.append(i)
if i >= k - 1:
ans.append(nums[q[0]])
return ans