数组中第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;
     }
}

猜你喜欢

转载自www.cnblogs.com/wen-/p/12713900.html