Given an array nums, there is a sliding window of size K which are moving from the very left of the array To the very right. You can only see the K numbers in the window. Each of 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 are always valid, Ie:1≤k≤input array's size for non-empty array.
Follow up:
Could solve it in linear time?
Similar:
Minimum Window Substring
155. Min Stack
159. Longest Substring with at most Distinct characters
265. Paint House II
1Solution 1. Priority Queue2 Public classSolution {3 classPairImplementsComparable<pair>{4 Public intkey;5 Public intidx;6 7 PublicPair (intKintID) {8 This. Key =K;9 This. idx =ID;Ten } One A @Override - Public intcompareTo (Pair p) { - return This. Key < P.key? 1: ( This. Key = = P.key? 0:-1);//reverse order, from Large to Small the } - } - - Public int[] Maxslidingwindow (int[] Nums,intk) { + if(Nums.length = = 0 | | k <= 0)return New int[0]; - +Priorityqueue<pair> que =NewPriorityqueue<pair>(); A int[] ret =New int[Nums.length-k + 1]; at inti = 0; - - for(i = 0; i < nums.length; i++) { -Que.add (NewPair (Nums[i], i)); - while(Que.peek (). idx < I-k + 1) { - Que.poll (); in } - if(I >= k-1) { toRET[I-K+1] =Que.peek (). Key; + } - } the * returnret; $ }Panax Notoginseng}
239. Sliding Window Maximum