Topic
Given an array and the size of the sliding window, find the maximum value of the values in all the sliding windows. For example, if you enter the array {2,3,4,2,6,2,5,1} and the size of the sliding window 3, there are 6 sliding windows, their maximum value is {4,4,6,6,6,5}, and the sliding window for the array {2,3,4,2,6,2,5,1} has the following 6: {[ 2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[ 2,5,1]}.
1 PackageCom.exe8.offer;2 3 4 ImportJava.util.ArrayDeque;5 Importjava.util.ArrayList;6 7 Public classMaxnuminwindow {8 9 PublicArraylist<integer> Maxinwindows (int[] num,intsize) {TenArraylist<integer> maxlist =NewArraylist<integer>(); One if(Size <= 0)returnmaxlist; A //Create a double-ended queue to save the maximum worth of subscript for each sliding window -arraydeque<integer> queue =NewArraydeque<integer>(); - //Create a variable start to record the maximum value of the current sliding window subscript the intStart = 0; - for(inti = 0; i < num.length; i++) { -Start = i + 1-size;//when start is greater than that, the first window is no longer moving. - if(Queue.isempty ()) { + Queue.add (i); -}Else if(Start > Queue.peekfirst ()) {//This condition indicates that the value of the start of the current window is greater than the start of the previous window + Queue.pollfirst (); A } at - while(!queue.isempty () && num[queue.peeklast ()] <=Num[i]) { - //This situation indicates that the element corresponding to the queue's tail position is smaller than the current element, so remove him, because the maximum window value needs to be - queue.polllast (); - } - Queue.add (i); in if(Start >= 0){ - //In fact, when start=0 first sliding window, then the queue is saved in the first sliding window the maximum value of the subscript, directly add the line to Maxlist.add (Num[queue.peekfirst ()); + } - } the returnmaxlist; * } $ Panax Notoginseng Public Static voidMain (string[] args) { - int[] num = {2,3,4,2,6,2,5,1}; thearraylist<integer> list =NewMaxnuminwindow (). Maxinwindows (NUM, 3); + System.out.println (list); A } the}
Sword refers to the maximum value of the----sliding window of the offer series (Don't understand??????????????????????????????????????????????????????????? )