https://leetcode-cn.com/problems/sliding-window-maximum/
采用双向队列的方法,代码 如下
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0 || nums.length < k) {
return new int[0];
}
int[] result = new int[nums.length - k + 1];
LinkedList<Integer> queue = new LinkedList<>();
for(int i = 0; i < nums.length; i++) {
/// 去除队列中一些永远不会起作用的元素,如[5,3]这时如果下一个元素是6,那么5,3永远不会是滑动窗口中最大的那个元素
while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
queue.pollLast();
}
/// 将当前的元素添加到滑动窗口
queue.add(i);
/// 这里其实很巧妙,作用有2
/// 1. 永远使得滑动窗口的元素数量不超过size
/// 2. 如果有元素是已经失效的元素,也就是与当前的i的距离超过k了,但是因为前面的poll操作使得他仍处于这个滑动窗口中,那么将它去除
if(queue.peek() <= i-k) {
queue.poll();
}
/// 前k-1个不需要计算
if(i >= k-1) {
result[i+1-k] = nums[queue.peek()];
}
}
result[result.length-1] = nums[queue.peek()];
return result;
}
}