【重点】【滑动窗口】239. 滑动窗口最大值
题目
也可参考:剑指offer——面试题65:滑动窗口的最大值
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] res = new int[nums.length - k + 1];
Deque<Integer> q = new LinkedList<>();
int inx = 0;
while (inx < k) {
if (q.isEmpty()) {
q.offerLast(nums[inx++]);
} else {
while (!q.isEmpty() && q.peekLast() < nums[inx]) {
q.pollLast();
}
q.offerLast(nums[inx++]);
}
}
res[0] = q.peekFirst(); // inx - k
while (inx < nums.length) {
int d = nums[inx - k];
if (q.peekFirst() == d) {
q.pollFirst();
}
while (!q.isEmpty() && q.peekLast() < nums[inx]) {
q.pollLast();
}
q.offerLast(nums[inx++]);
res[inx - k] = q.peekFirst();
}
return res;
}
}