题目:
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7]
, and k = 3.
Window position Max --------------- ----- [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
Therefore, return the max sliding window as [3,3,5,5,6,7]
.
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
分析:
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
//给定数组,和滑动窗口大小,每次滑动窗口只能滑动一个。
//思路:使用暴力解法,那么每次需要查找k次,整个事件复杂度为O(nk)。更加巧妙的解法,使用双端队列Deque来实现
//Deque可以在两头进行队列的操作,不过该队列存储的对应下标。用来保存可能是窗口最大的值的下标
//精简版
if(nums==null||nums.length==0||k>nums.length) return new int[0];
int [] res=new int[nums.length-k+1];
int count=0;
//定义一个双端队列
Deque<Integer> dq=new LinkedList<>();
for(int i=0;i<nums.length;i++){
//判断队列是否存在元素,且队列尾的元素不能小于当前处理元素
while(!dq.isEmpty()&&nums[i]>=nums[dq.peekLast()]){
//队尾出
dq.pollLast();
}
//再判断对头元素下标是否过期了
if(!dq.isEmpty()&&dq.peek()<i-k+1){
//已经过期了,剔除
dq.poll();
}
//添加当前处理元素
dq.add(i);
//取对头元素作为最大值放入结果集,使用队列的话,前面k-1的不进行赋值。例如3个元素,最大只有一个,那么2个是不需要赋值的
if(i>=k-1){
res[count++]=nums[dq.peek()];
}
}
return res;
}
}