C++(0ms) Ugly code...


  • 0
    R
    //Main idea is to store every digit from right to left, while in the mean time, try to find if there is any digit that's bigger than this digit but appears before this one.
    #include <map>
    class Solution {
    public:
        int nextGreaterElement(int n) {
            int m[10]={0}; 
            int t,md=0; //md is the so far the biggest digit
            while(n){
                t=n%10;
                if(t<md) break;
                md=t;
                m[t]++;
                n/=10;
            }
            if(n==0) return -1; //There is no such positive 32-bit integer 
            m[t]++;
            n/=10;
            int tmp=md;
            while(--tmp>t) if(m[tmp]) md=tmp;
            long nn=n;
            nn=nn*10+md;
            m[md]--;
            for(int i=0;i<=9;i++){
                while(m[i]){
                    nn = nn*10+i;
                    m[i]--;
                }
            }
            return nn>INT_MAX?-1:nn;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.