Given an arraynums, 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,
Givennums=[1,3,-1,-3,5,3,6,7]
, andk= 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?
tag: 单调栈
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0) return new int[0];
int n = nums.length;
int[] res = new int[n];
Deque<Integer> dq = new ArrayDeque<Integer>();
for (int i = 0; i < k - 1; i++){
inQueue(dq, nums[i]);
}
int index = 0;
for (int i = k - 1; i < n; i++){
inQueue(dq, nums[i]);
res[index++] = dq.peekFirst();
outQueue(dq, nums[i - k + 1]);
}
int[] ans = new int[index];
for (int i = 0; i < index; i++){
ans[i] = res[i];
}
return ans;
}
private void inQueue(Deque<Integer> dq, int num){
while (!dq.isEmpty() && dq.peekLast() < num){
dq.pollLast();
}
dq.offer(num);
}
private void outQueue(Deque<Integer> dq, int num){
if (dq.peekFirst() == num) dq.pollFirst();
}
}