239 Sliding Window Maximum

1. Question

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, Givennums=[1,3,-1,-3,5,3,6,7], andk= 3.
1
Window position Max
2
--------------- -----
3
[1 3 -1] -3 5 3 6 7 3
4
1 [3 -1 -3] 5 3 6 7 3
5
1 3 [-1 -3 5] 3 6 7 5
6
1 3 -1 [-3 5 3] 6 7 5
7
1 3 -1 -3 [5 3 6] 7 6
8
1 3 -1 -3 5 [3 6 7] 7
Copied!
Therefore, return the max sliding window as[3,3,5,5,6,7].
Note: You may assumekis always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
Follow up: Could you solve it in linear time?

2. Implementation

(1) Heap with PriorityQueue
1
class Solution {
2
public int[] maxSlidingWindow(int[] nums, int k) {
3
if (nums == null || nums.length == 0) {
4
return new int[0];
5
}
6
7
int n = nums.length;
8
int[] res = new int[n - k + 1];
9
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
10
11
for (int i = 0; i < n; i++) {
12
maxHeap.add(nums[i]);
13
14
if (i >= k) {
15
maxHeap.remove(nums[i - k]);
16
}
17
18
if (i - k + 1 >= 0) {
19
res[i - k + 1] = maxHeap.peek();
20
}
21
}
22
return res;
23
}
24
}
Copied!
(2) Heap with TreeMap
1
class Solution {
2
public int[] maxSlidingWindow(int[] nums, int k) {
3
if (nums == null || nums.length == 0) {
4
return new int[0];
5
}
6
7
int n = nums.length;
8
int[] res = new int[n - k + 1];
9
10
TreeMap<Integer, Integer> map = new TreeMap();
11
12
for (int i = 0; i < n; i++) {
13
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
14
15
if (i >= k) {
16
map.put(nums[i - k], map.get(nums[i - k]) - 1);
17
if (map.get(nums[i - k]) == 0) {
18
map.remove(nums[i - k]);
19
}
20
}
21
22
if (i - k + 1 >= 0) {
23
res[i - k + 1] = map.lastKey();
24
}
25
}
26
return res;
27
}
28
}
Copied!
(3) Deque
1
class Solution {
2
public int[] maxSlidingWindow(int[] nums, int k) {
3
if (nums == null || nums.length == 0) {
4
return new int[0];
5
}
6
7
int n = nums.length;
8
int[] res = new int[n - k + 1];
9
10
ArrayDeque<Integer> deque = new ArrayDeque();
11
int index = 0;
12
13
for (int i = 0; i < n; i++) {
14
// Remove index that is out of slinding window
15
while (!deque.isEmpty() && deque.peek() < (i - k + 1)) {
16
deque.remove();
17
}
18
19
// Remove number which is smaller than the current number since they won't be the max
20
while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
21
deque.removeLast();
22
}
23
24
deque.add(i);
25
26
if (i - k + 1 >= 0) {
27
res[index++] = nums[deque.peek()];
28
}
29
}
30
return res;
31
}
32
}
Copied!

3. Time & Space Complexity

Heap with PriorityQueue: 时间复杂度O(n*k),PriorityQueue.remove(Object)要O(k)的时间,而PriorityQueue.remove()需要O(logk)的时间, 空间复杂度O(n) Heap with TreeMap: 时间复杂度O(nlogk), 空间复杂度(n) TreeMap需要O(k)空间, res需要n - k + 1空间,加起来要O(n)
Deque: 时间复杂度O(n), 空间复杂度O(n)