Leetcode Sliding Window Maximum
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 thek numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
|
1 2 3 4 5 6 7 8 9 |
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?
Hint:
- How about using a data structure such as deque (double-ended queue)?
- The queue size need not be the same as the window’s size.
- Remove redundant elements and the queue should store only elements that need to be considered.
Analysis
The algorithm is described as follows:
for i from 0 to nums.length;
- if the queue is not empty, and the head of the queue equals to i - k, remove the queue head
- while the queue is not empty, keep removing the end of the queue until
nums[q.end()]is larger thannum[i]- add i to the end of the queue
- if (i - k + 1 >=0) append nums[q.first()] to the result list.
See the following figure to better understand the process:
We can see that, the numbers in the queue is sorted, and the head of the queue is the biggest number in the window.
Java Solution:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(k == 0) return new int[0]; LinkedList<Integer> window = new LinkedList<>(); int[] res = new int[nums.length - k + 1]; for(int i = 0; i < nums.length; i++) { if(window.size() > 0 && window.peekFirst() == i - k) { window.pollFirst(); } while(window.size() > 0 && nums[window.peekLast()] <= nums[i]) { window.pollLast(); } window.add(i); if(i - k + 1 >= 0) { res[i - k + 1] = nums[window.peekFirst()]; } } return res; } } |











