My C++ 12ms soluton


  • 0
    D

    The basic idea is to find the right sub-vector that is in the reverse order; reverse the sub-vector, and swap the element just before the subvector with the first element that is larger than it in the sub-vector.

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int len= nums.size(), start = len-2, i;
            while(start>=0 && nums[start]>=nums[start+1]) --start;
            std::reverse(nums.begin() + start + 1,nums.end());
            if(start>=0) 
            {
                for(i=len-2; nums[i]> nums[start];--i);
                swap(nums[start], nums[i+1]);
            }
        }
    };

Log in to reply
 

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