https://leetcode-cn.com/problems/sliding-window-maximum/
用单调队列来做,学习到了单调队列!终于遇到hard了,原来都是套路
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
MyQueue myQueue = new MyQueue();
if(nums.length == 1) return nums;
int[] res = new int[nums.length - k + 1];
int j = 0;
for(int i = 0;i < k;i++){
myQueue.push(nums[i]);
}
res[j++] = myQueue.front();
for(int i = 1; i < nums.length - k + 1;i++){
myQueue.pop(nums[i - 1]);
myQueue.push(nums[i + k - 1]);
res[j++] = myQueue.front();
}
return res;
}
}
class MyQueue{
Deque<Integer> queue = new LinkedList<>();
void pop(int val){
if(val == queue.getFirst() && !queue.isEmpty()){
queue.pollFirst();
}
}
void push(int val){
while(!queue.isEmpty() && val > queue.getLast()){
queue.pollLast();
}
queue.addLast(val);
}
int front(){
return queue.getFirst();
}
}
思路:
1.先自己构建单调队列,滑动窗口的pop和push函数。
2.pop函数,如果要pop的val等于最大值(队列头),就pop掉,如果不是,就不修改队列
3.push函数,如果要push的val比队列尾巴大,就把尾巴去掉,直到val等于或者小于,又或者队列空了,再push这个val,保证队列中的头永远是滑动窗口中的最大值。
4.主函数思路,先构建滑动窗口,特殊处理第一个最大值,后续用for循环操作,注意数组下标的问题,特判nums.length == 1的情况即可。
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> queue = new LinkedList<>();
if(nums.length == 1) return nums;
int[] res = new int[nums.length - k + 1];
int front,later;
int j = 0;
for(int i = 0;i < k;i++){
while(!queue.isEmpty() && nums[i] > queue.getLast()){
queue.pollLast();
}
queue.addLast(nums[i]);
}
res[j++] = queue.getFirst();
for(int i = 1; i < nums.length - k + 1;i++){
later = nums[i - 1];
front = nums[i + k - 1];
if(!queue.isEmpty() && later == queue.getFirst()) queue.pollFirst();
while(!queue.isEmpty() && front > queue.getLast()){
queue.pollLast();
}
queue.addLast(front);
res[j++] = queue.getFirst();
}
return res;
}
}
直接把单调队列写进主函数里,运行速度快了不少诶,代码可读性还是前者好,运行速度是后者快