Leetcode 31: Next Permutation

31. Next Permutation

  • Total Accepted: 87393
  • Total Submissions: 313398
  • Difficulty: Medium
  • Contributors: Admin

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

 

Code

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        # find the last number that nums[i] > nums[i-1]
        i = len(nums)-1
        while i > 0:
            if nums[i] > nums[i-1]:
                break
            i -= 1
        
        # no nums[i] > nums[i-1] found. Reverse whole array
        if i == 0:
            self.reverse_sort(nums, 0, len(nums))
            return
        
        # find the last number that nums[j] > nums[i-1]
        for j in xrange(len(nums)-1, i-1, -1):
            if nums[j] > nums[i-1]:
                nums[i-1], nums[j] = nums[j], nums[i-1]
                break
        
        self.reverse_sort(nums, i, len(nums))
    
    def reverse_sort(self, nums, start, end):
        """ 
        Reverse the order in the range
        start: inclusive, end: exclusive 
        """
        mid = start + (end - start) / 2
        for i in xrange(start, mid):
            j = len(nums)-1-i+start
            nums[i], nums[j] = nums[j], nums[i]
         

 

Idea

See comments and the plot for an example 125431:

rrrrev

Reference: https://discuss.leetcode.com/topic/2542/share-my-o-n-time-solution

Leave a comment

Your email address will not be published. Required fields are marked *