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.

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 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

(2) Heap with TreeMap

(3) Deque

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)

Last updated

Was this helpful?