C++ 4 lines (next_permutation)


  • 12
    V
    int nextGreaterElement(int n) {
        auto digits = to_string(n);
        next_permutation(begin(digits), end(digits));
        auto res = stoll(digits);
        return (res > INT_MAX || res <= n) ? -1 : res;
    }
    

  • 3
    P

    表示受到一万点暴击。。。。。。。。。。


  • 0
    L

    +1....................


  • 0
    D

    If you know next_permutation, this problem somehow becomes a easy question.


  • 0
    J

    I think that the question is asking you to interpret the next permutation in your own way. One should check leetcode question 31. I don't believe that any interviewer will be satisfied by this answer.


  • 0
    V

    @justin40 I think that the point of this problem is to recognize and apply the next premutation. Problem 31, in contrary, specifically asks to implementation next premutation.

    As an interviewer, I would add points if a candidate is familiar with next_permutation. I may ask to implement it, but probably I would just move on to more interesting problems.


  • 0
    B
    This post is deleted!

  • 0
    W

    There are this kind of operations !


  • 0
    I

    @pance +10086


  • 0

    What kind of solution is this?!


  • 1
    M

    With next_permutation implemented myself

    class Solution {
    public:
        int nextGreaterElement(int n) {
            string nums = to_string(n);
            if(!nextPermutation(nums)) return -1;
            long long result=stoll(nums);
            return (result>INT_MAX || result<=n)? -1:result;
        }
    private:
        bool nextPermutation(string& nums) {
            if(nums.empty()) return false;
            int i=nums.size()-1;
            while(i>=1 && nums[i]<=nums[i-1]) i--;
            if(i==0) return false; // no next permutation, i.e. already largest
            
            int j=nums.size()-1;
            while(nums[j]<=nums[i-1]) j--;
            swap(nums[i-1],nums[j]);
            
            reverse(nums.begin()+i,nums.end());
            return true;
        }
    };
    

Log in to reply
 

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