[LeetCode]Sliding Window Maximum - EpoTalk
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 the k 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.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?
分析
这种针对sliding window里的元素的题目往往都用Queue解决。
这道题是求window内的最大值,比较brute force的方法就是维护一个Priority Queue, 然后每次找最大值,随着window移动不断删除和增加相应元素。但是这样做的话时间复杂度会相对较高,因为对于Priority Queue而言,删除指定object的复杂度是O(n)。
那么我们可以考虑设计一个MaxQueue, 移动window过程中不断更新递减的最大值。这种思路比较好的实现方法是用Deque数据结构, queue里存着以当前值index结尾依次递减的值的index。当window里有新元素增加的时候,我们更新queue里的index,更新方法是从尾部不断pop出比新加入进来的元素小的元素的index。
类似的这种sliding window的题还有很多,比如求window里的平均值,同样用queue也可以解决。
复杂度
time: O(n), space: O(n)
代码
public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if (k <= 0 || nums == null)return nums; int[] res = new int[nums.length - k + 1]; Deque<Integer> dq = new ArrayDeque<>(); int j = 0; for (int i = 0; i < nums.length; i++) {// 删除window外的元素的indexif (!dq.isEmpty() && dq.peek() < i - k + 1) { dq.remove();}// 更新queue里的index,使得queue中index对应值依次递减while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) { dq.removeLast();}dq.add(i);// 取得当前window里的最大值if (i >= k - 1) res[j++] = nums[dq.peek()]; } return res; }}