The maximum sliding window: to prove safety

Title Description

Given an array of size and sliding window, find the maximum value of all sliding window.

For example, if the input array  [2, 3, 4, 2, 6, 2, 5, 1] size and sliding window 3, then the presence of a total of six sliding window, the maximum value thereof, respectively  [4, 4, 6, 6, 6, 5].

note:

  • Data assurance k greater than 0 and less than or equal k array length.

Sample

输入:[2, 3, 4, 2, 6, 2, 5, 1] , k=3

输出: [4, 4, 6, 6, 6, 5]


solution

Using a double-ended queue to ensure the maximum head of the queue is stored in the index, the head of the queue when the pop-up index expired.

detail:

  • When the head of the queue is less than the array elements corresponding to elements of the subscript, subscript of the array element is inserted in the tail of the queue. (If the queue is less than the tail element of that element, the first pop up, and then insert.)
  • When the elements are greater than or equal to the array element constituting the head of the queue when the subscript, pop-up element until the queue is empty, then insert the subscript of the array element.

 

 

Import Classes in java.util *. ;
 public  class Solution {
     / ** 
with a double-ended queue, the first queue position to save a maximum current window, when a sliding window 
1 determines whether a current maximum expiration 
2. New values comparison begins at the tail, all smaller than the value of his lost 
* / 
    public the ArrayList <Integer> maxInWindows ( int [] NUM, int size) 
    { 
        IF (NUM == null || num.length size == 0 || < size || 0 => num.length) {
             return  new new the ArrayList <Integer> (); 
        } 
        
        the ArrayList <Integer> = RES new new the ArrayList <> (); 
        
        the LinkedList <Integer> = Qmaxnew LinkedList<>();
        
        for(int i=0; i<num.length; i++){
            while(!qmax.isEmpty() && num[qmax.peekLast()] < num[i]){
                qmax.pollLast();
            }
            qmax.addLast(i);
            
            //判断队首元素是否过期
            if(qmax.peekFirst() == i-size){
                qmax.pollFirst();
            }
            
            if(i+1>=size){
                res.add(num[qmax.peekFirst()]);
            }
        }
        
        return res;
    }
}

 

 

 

 

Guess you like

Origin www.cnblogs.com/lisen10/p/11415610.html