LC.P239[滑动窗口最大值]

方法一:滑动窗口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length < 2) return nums;
Deque<Integer> queue = new ArrayDeque<>();
int n = nums.length;
int[] ans = new int[n - k + 1];
for (int i = 0; i < n; ++i) {
// 队列内从大到小
while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) {
queue.pollLast();
}
queue.offerLast(i);
if (queue.peekFirst() <= i - k) {
queue.pollFirst();
}
// 窗口形成
if (i + 1 >= k) {
ans[i + 1 - k] = nums[queue.peekFirst()];
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(k)$