C++ 3ms, no long int O(n) Solution


  • 0
    M
    int nextGreaterElement(int n) {
            string s=to_string(n);
            for(int i=s.size()-1;i>0;i--) {
                if(s[i]>s[i-1]) {
                    for(int j=s.size()-1;j>=i;j--) {
                        if(s[j]>s[i-1]) {
                            swap(s[j], s[i-1]);
                            break;
                        }
                    }
                    int start=i, end=s.size()-1;
                    while(start<end) {
                        char temp=s[start];
                        s[start++]=s[end];
                        s[end--]=temp;
                    }
                    if(s.size()==10) {
                        if(stoi(s.substr(0, s.size()-1))>INT_MAX/10) return -1;
                        else if(stoi(s.substr(0, s.size()-1))==INT_MAX/10&&s[s.size()-1]-'0'>INT_MAX%10) return -1;
                    }
                    return stoi(s);
                }
            }
            return -1;
        }

Log in to reply
 

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