239. Sliding Window Maximum
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?
这道题是 hard 难度,要解决也是想了很久,主要还是依靠 tag 给的思路
使用 stack,基本原则就是保持 stack 的大小是 k,同时每次添加新的元素,可以将比它小的元素都去掉。保证了窗口大小内总是最大的在顶端。
然而 stack 存在的问题是只能对栈顶进行操作,当stack 尺寸大于 k 时,我们无法有效去除底部元素。对于首尾都需要操作的情况,一个有效的数据结构就是 dequeue。他保证了数据的首尾都能够有效利用。
为了保持数列信息,我们存入的是所在元素的位置而不是数值。
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0 ||k == 0){
return nums;
}
int index = 0;
int[] res = new int[nums.length - k + 1];
Deque<Integer> win = new LinkedList();
for(int i = 0 ; i < nums.length; i++){
while(!win.isEmpty() && win.peek() < i - k + 1){
win.poll();
}
while(!win.isEmpty() && nums[win.peekLast()] < nums[i]){
win.pollLast();
}
win.offer(i);
if(i>=k -1){
res[index++] = nums[win.peek()];
}
}
return res;
}
}