当前位置:网站首页>2022.7.3-----leetcode. five hundred and fifty-six

2022.7.3-----leetcode. five hundred and fifty-six

2022-07-04 05:55:00 Lu 727

 public int nextGreaterElement(int n) {
        if(n<10) return -1;
        int num=n;// Save original number 
        // Split the numbers in reverse order 
        int idx=0;
        int[] arr=new int[String.valueOf(n).length()];
        while(n>0){
            arr[idx++]=n%10;
            n/=10;
        }
        // Start from the low position at [0,i-1] The range search is greater than arr[i] Replace with the smallest number of arr[i], Then sort the following from large to small 
        for(int i=1;i<arr.length;i++){
            int k=0;// Decimal index 
            int min=10;// Greater than arr[i] The minimum value of 
            for(int j=0;j<i;j++){
                if(arr[j]>arr[i]&&arr[j]<min){
                    min=arr[j];
                    k=j;
                }         
            }
            if(min==10) continue;// Can't find , It means that this bit must be followed by order 
            // And arr[i] In exchange for 
            int tmp1=arr[k];
            arr[k]=arr[i];
            arr[i]=tmp1;
            // Sort the following numbers 
            for(int l=i-1;l>0;l--){
                boolean ex=false;
                for(int j=0;j<l;j++){
                if(arr[j]<arr[l]){
                    int tmp2=arr[j];
                    arr[j]=arr[l];
                    arr[l]=tmp2;
                    ex=true;
                }
                }
                if(!ex) break;
            }
            break;// Go back when you find it 
        }
        // synthesis 
        long ans=0;
        for(int i=arr.length-1;i>=0;i--){
            ans=ans*10+arr[i];
        }
        // Judge whether it is legal 
        if(ans==num||ans>Integer.MAX_VALUE) return -1;
        return (int)ans;

    }

原网站

版权声明
本文为[Lu 727]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040553020410.html