class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0) return new int[0];
int[] result = new int[nums.length - k + 1];
Deque<Integer> queue = new ArrayDeque();
// i:记录nums j:记录result
for(int i = 0, j = 0; i < nums.length; i++){
// poll():查看后删除 pop():只查看不删除
// 数量大于滑动窗口大小,去掉多余的
if(!queue.isEmpty() && i - queue.peek() >= k) queue.poll();
// 找到最大值,注意得是peekLast和poolLast,nums[i]>后面的
while(!queue.isEmpty() && nums[i] > nums[queue.peekLast()]) queue.pollLast();
queue.add(i);
if(i >= k - 1) result[j++] = nums[queue.peek()];
}
return result;
}
}
剑指offer59.Ⅰ滑动窗口的最大值。简单易懂注释版0ms
本文介绍了一种求解滑动窗口中最大值的高效算法。通过使用双端队列来跟踪当前窗口内的元素,该算法能够在O(n)的时间复杂度内完成计算。具体实现上,我们维护了一个双端队列,用来保存窗口内的元素下标,并确保队列头部始终为当前窗口的最大值。

被折叠的 条评论
为什么被折叠?



