给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
输入: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
单调队列
class MyQueue{
Deque<Integer> queue = new LinkedList<>();
如果弹出的元素是当前队列最大值,才会真正弹出
void pop(int element){
if(!queue.isEmpty() && queue.peek().equals(element)){
queue.poll();
}
}
void push(int element){
while(!queue.isEmpty() && element>queue.getLast()){
queue.removeLast();
后续压入的元素比之前压入的元素大,之前的元素就毫无价值了
所有队列左大右小,如果右大,左边就被清楚了
}
queue.add(element);
}
int peek(){
return queue.peek();
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length==1){
return nums;
}
MyQueue myQueue = new MyQueue();
int[] res = new int[nums.length-k+1];
for (int i = 0; i < k; i++) {
myQueue.push(nums[i]);
}
int index= 0;
res[index++] = myQueue.peek();
for (int i = k; i <nums.length; i++) {
myQueue.pop(nums[i-k]);
myQueue.push(nums[i]);
res[index++] = myQueue.peek();
}
return res;
}
}