问题描述
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
问题解决
使用双向队列,进行滑动窗口操作
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
//通过维护一个由大到小双端队列实现,注意:队列存储的是index
if(nums == null || nums.length == 0) return new int[0];
if(k == 1) return nums;
int[] res = new int[nums.length - k + 1];
//双端队列
Deque<Integer> deque = new LinkedList<>();
int index = 0, t = 0;
while(index < nums.length) {
//1、首先判断滑动窗口大小是否越界,若越界,出队
if(!deque.isEmpty() && index - deque.peekFirst() >= k) deque.removeFirst();
//2.维护一个重大到小的双端队列,若栈顶较小,出栈
while(!deque.isEmpty() && nums[index] > nums[deque.peekLast()])
deque.removeLast();
//3.入队操作
deque.addLast(index);
//4.获取队列头作为最大值返回
if(index >= (k - 1)) {
res[t++] = nums[deque.peekFirst()];
}
index++;
}
return res;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。