解题思路
B站视频讲解:https://www.bilibili.com/video/BV1MW4y1b7rA/?vd_source=a0bea6f5def58dc5711647a825ed97b6
LeetCode239_滑动窗口最大值_单调栈
代码
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] result = new int[nums.length - k + 1];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[i] >= nums[stack.peek()]) {
stack.pop();
}
stack.push(i);
// 滑动窗口的左下标
int left = i - k + 1;
// 代表有上个窗口的残留栈底,需要进行清理
if (left > stack.peekLast()) {
// 清理残留栈底
stack.removeLast();
}
if (left >= 0) {
// 当前栈底就是当前滑动窗口的最大值
result[left] = nums[stack.peekLast()];
}
}
return result;
}
}