[556. Next Greater Element III] C++_Next Permutation


  • 0
    class Solution {
    public:
    int nextGreaterElement(int n) {
        if(n <= 11) return -1;
        string num = to_string(n);
        //next permutation
        for(int i = num.size() - 2; i >= 0; --i){
            if(num[i] < num[i+1]){
                for(int j = num.size()-1; j > i; --j){
                    if(num[i] < num[j]){
                        swap(num[i], num[j]);
                        reverse(num.begin() + i + 1, num.end());
                        break;
                    }
                }
                break;
            }
        }
        long res = stol(num);
        return (res >= INT_MAX || res == n)? -1 : res;
    }
    };

Log in to reply
 

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