This is my answer,12ms using C++,sort() is fast than reverse() when the sequence is reversed


  • 0
    Z
    void nextPermutation(vector<int>& nums) 
    {
            if(nums.size() < 2)
                return;
            int len = nums.size();
            int k = len - 2;
            while(k >= 0 && nums[k] >= nums[k+1])
             k--;
            if(k < 0)
            {
              sort(nums.begin(),nums.end());
              return;
            }
            int i = len -1;
            while(i > k && nums[i] <= nums[k])
              --i;
            swap(nums[i],nums[k]);
            reverse(nums.begin()+k+1,nums.end());
    }

Log in to reply
 

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