c++ neat and efficient solution.


  • 2
    • Implements steps:
      Find largest index i where nums[i] < nums[i + 1]
      Find lasgest index j after i where nums[j] > nums[i]
      Swap node nums[i] and nums[j]
      Reverse from index i to the end.
    class Solution {
    public:
      void nextPermutation(vector<int>& nums) {
        int n = nums.size();
    
        int i = n - 1;
        int j = n - 1;
        while (i > 0)
        {
          if (nums[i] > nums[i - 1])
          {
    	while (j > i - 1)
    	{
    	  if (nums[j] > nums[i - 1])
    	  {
    	    swap(nums[i - 1], nums[j]);
    	    reverse(nums.begin() + i, nums.end());
    	    return;
    	  }
    	  j --;
    	}  
          }
          i --;
        }
        reverse(nums.begin(), nums.end());
      }
    };
    

  • 0
    N

    Reverse i+1 to end.


Log in to reply
 

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