Share my C++ solution


  • 0
    V
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int n = nums.size();
            if (n < 2)
                return;
                
            int i = n - 1, j = 0, left = 0;
           
            while (i > 0 && nums[i-1] >= nums[i])
                i--;
            
            if (i != 0)
            {
                left = i;
                j = n - 1;
                
                while (nums[left-1] >= nums[j] )
                    j--;
                
                swap(nums[left-1], nums[j]);
            }
            reverse(nums.begin()+left, nums.end());
        }
    };

Log in to reply
 

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