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].
一刷
题解:
用一个队列保存index
队首用来移除在范围k之外的元素
队尾用来与新加入的元素比较,如果小于新加入的元素,移除,保证队首的元素是k之内最大的
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
if(len == 0 || k<=0) return new int[0];
int index = 0;
int[] res = new int[len - k + 1];
Deque<Integer> queue = new ArrayDeque<>();
for(int i=0; i<len; i++){
if(!queue.isEmpty() && queue.peek()<=i-k) queue.poll();
while(!queue.isEmpty() && nums[queue.peekLast()]<nums[i]) queue.pollLast();
queue.offer(i);
if(i>=k-1){
res[index] = nums[queue.peek()];
index++;
}
}
return res;
}
}
二刷同上
一刷的方法非常巧妙
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> q = new ArrayDeque<>(k);
int len = nums.length;
if(len == 0 || k == 0) return new int[0];
int[] res = new int[len - k + 1];
for(int i=0; i<len; i++){
if(!q.isEmpty() && q.peekFirst()+k==i) q.pollFirst();
while(!q.isEmpty() && nums[q.peekLast()]<= nums[i]) q.pollLast();
q.offer(i);
if(i>=k-1){
res[i-k+1] = nums[q.peekFirst()];
}
}
return res;
}
}