The maximum value of the sliding window (stacks and queues): offer to prove safety

1. Title Description

/ * 
    Given an array and the size of the sliding window, sliding window to find the maximum value among all values. 
    For example, if the input array size and {2,3,4,2,6,2,5,1} 3 sliding window, then the presence of a total of six sliding window, their maximum values is {4,4,6, 6,6,5}; 
    it has the following six array {2,3,4,2,6,2,5,1} for the sliding window: 
  {[2,3,4], 2,6,2,5 , 1},
  {2, [3,4,2], 6,2,5,1},
  {2,3, [4,2,6], 2, 5},
  {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. Ideas

/ ** 
 * Title: maximum sliding window 
 * idea: the sliding window should be a queue, in order to obtain the maximum value of the sliding window, the queue elements from both ends of the sequence may be deleted, so use deque. 
 * Principle: 
 * c for the new elements, it is compared with the double-ended queue element 
 * 1) rear (tail of the queue) is smaller than c, x, is directly removed from the queue (it is no longer behind the sliding window may be the maximum value);! 
 * 2) in front of (the head of the queue) is larger than X c, compare the two subscripts, X is determined whether or not within the window, gone directly dequeued; 
 * 3) of the queue element is the maximum value in the sliding window. 
 * /

 

3. Code

Import Classes in java.util *. ;
 public  class Solution {
     public the ArrayList <Integer> maxInWindows ( int [] NUM, int size) {
         IF (NUM == null || num.length size == 0 || <|| NUM = 0 .length < size) {
             return  new new the ArrayList <Integer> ; () 
        } 
        the ArrayList Result = <Integer> new new the ArrayList <> ();
         // deque is used to record the maximum value of the subscript of each window 
        LinkedList <Integer> = Qmax new new the LinkedList <> ();
         int index = 0;
         For ( int I = 0; I <num.length; I ++ ) {
             // if the queue is not empty and the last element of the queue <current value, it is no longer possible because the maximum value of the sliding window behind 
            the while (Qmax! .isEmpty () && NUM [qmax.peekLast ()] < NUM [I]) { 
                qmax.pollLast (); 
            } 
            qmax.addLast (I); 
            // Analyzing element head of the queue has expired 
            the while (qmax.peekFirst () < I = - size) { 
                qmax.pollFirst (); 
            } 
            // the above two while the first element to ensure the head of the queue is the maximum value of each window
             // save the maximum of each window (note: the size at -1) 
            IF (I> = size -. 1 ) {  
                result.add (NUM [qmax.peekFirst ()]);
            } 
        }
        return result;
    }
}

 

Guess you like

Origin www.cnblogs.com/haimishasha/p/11520681.html