C++ 15 lines 0ms with explanation


  • 0
    Z
        int nextGreaterElement(int n) {
            string s = to_string(n);
            int i = 0, p = 0, q = 0, len = s.length();
            while (++i < len) {
                if (s[i - 1] >= s[i]) { // e.g. 5698776665443, s[p] = '6', s[q] = '7'(the rightmost one)
                    if (s[i] > s[p]) q = i; // s[q] is the next greater number in the down sequence for s[p] 
                } else {
                    p = i - 1;
                    q = i;
                }
            }
            if (q == 0) return -1; // The sequence is descending
            swap(s[p], s[q]);
            reverse(s.begin() + p + 1, s.end()); // e.g. 5698776665443 -> 5798766665443 -> 5734456666789
            if (s.length() == 10 && s.compare(to_string(INT_MAX)) > 0) return -1;
            return stoi(s);
        }
    

Log in to reply
 

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