第十三天| 239. 滑动窗口最大值
题目关键字:单调队列(Deque)
239_题目链接:https://leetcode.cn/problems/sliding-window-maximum/
代码实现
package LeetCode;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class YangSibo_239 {
public static void main (String args []) {
YangSibo_239_1 demo = new YangSibo_239_1();
int nums [] = {1,3,1,2,0,5};
int k = 3;
int res [] = demo.maxSlidingWindow(nums,k);
for (int x:res) {
System.out.print(x + " ");
}
}
}
class YangSibo_239_1 {
public int[] maxSlidingWindow(int[] nums, int k) {
int length = nums.length;
YangDeqeue deqeue = new YangDeqeue();
for(int i = 0;i<((length < k)?length:k);i++){
deqeue.add(nums[i]);
}
if( length < k) {
int res []={deqeue.peek()};
return res;
}else {
int res []=new int[length -k +1];
int count = 0;
for(int i = k;i<length;i++) {
res[count++]=deqeue.peek();
deqeue.poll(nums[i-k]);
deqeue.add(nums[i]);
}
res[count++]=deqeue.peek();
return res;
}
}
}
class YangDeqeue {
private Deque<Integer> deque = new LinkedList<>();
void poll (int val) {
if( val == deque.peek()) {
deque.poll();
}
}
int peek () {
return deque.peek();
}
void add (int val) {
while(!deque.isEmpty() && val > deque.getLast() ){
deque.pollLast();
}
deque.add(val);
}
}
解题注意事项
1、熟悉Deqeue,了解可以通过getLast和pollLast对队列进行更新,自己写循环易错
2、单调队列是为了保证留下的都是可能为最大的值
3、做好异常场景判断,例如:返回的结果集的长度,k与nums.length的大小