力扣算法学习day08-1
239-滑动窗口最大值
题目
![image-20220128114914276](https://i-blog.csdnimg.cn/blog_migrate/8f34e477d0ac510461b2cad94e458942.png)
![image-20220128114936146](https://i-blog.csdnimg.cn/blog_migrate/b7459e63dda4bcf8821093a3cbb0ca07.png)
代码实现
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
MyQueue queue = new MyQueue();
int[] result = new int[nums.length - k + 1];
int j = 0;
for(int i = 0;i < nums.length;i++){
queue.offer(nums[i]);
j = i - k + 1;
if(i >= k - 1){
result[j] = queue.front();
queue.poll(nums[j]);
}
}
return result;
}
}
class MyQueue{
ArrayDeque<Integer> queue = new ArrayDeque<>();
public void poll(int val){
if(front() == val){
queue.poll();
}
}
public void offer(int val){
while(!queue.isEmpty() && queue.peekLast() < val){
queue.pollLast();
}
queue.offer(val);
}
public int front(){
return queue.peek();
}
}