Python solution according to approach 2 in the solution


  • 0
    J
    class Solution(object):
        def nextPermutation(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            
            if len(nums) == 1:
                return
            
            i = len(nums) - 1
            while i > 0:
                if nums[i] > nums[i - 1]: # look for the first ascedent incident backwardly
                    
                    AJ = nums[i] # look for the 'just' larger than a[i - 1] element in a[i:len(nums)]
                    j = i
                    for m in range(i, len(nums)):
                        if nums[m] <= AJ and nums[m] > nums[i-1]:
                            AJ = nums[m]
                            j = m
                    nums[j], nums[i - 1] = nums[i - 1], nums[j] # switch
                    
                    nums[i:] = nums[len(nums) - 1:(i - 1):-1] # reverse new a[i:len(nums)]
                    return
                i = i - 1
                
                 
            else:
                nums[:] = nums[::-1] # reverse the whole list
                return
    

Log in to reply
 

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