數組中第i個位置的數字至少往右走多少步才能遇到比它大的數字


給定一個整數數組,返回一個數組。該返回數組中第i個數字爲,原數組中第i個位置的數字至少往右走多少步才能遇到比它大的數字。若是遇不到或者已經處於最右的位置,則置爲-1。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
import  java.util.*;
 
public  class  Main{
     public  static  void  main(String[] args){
         Scanner in =  new  Scanner(System.in);
         int  n = in.nextInt();
         int [] d =  new  int [n];
         for ( int  i= 0 ; i<n; i++){
             d[i] = in.nextInt();
         }
         int [] ret = help(d);
         StringBuilder sb =  new  StringBuilder();
         for ( int  i= 0 ; i<ret.length; i++){
             sb.append(ret[i]).append( "\n" );
         }
         System.out.print(sb.toString());
     }
     
     private  static  int [] help( int [] nums){
         int [] ret =  new  int [nums.length];
         Arrays.fill(ret, - 1 );
         Stack<Integer> s =  new  Stack<>();
         for ( int  i= 0 ; i<nums.length; i++){
             while (!s.isEmpty() && nums[i] > nums[s.peek()]){
                 int  top = s.pop();
                 ret[top] = i - top;
             }
             s.push(i);
         }
         return  ret;
     }
}
相關文章
相關標籤/搜索