My C++ 12ms soluton

  • 0

    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 {
        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());
                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.