31. Next Permutation

The next permutation of an array of integers is the next lexicographically greater permutation of its integer. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

  • For example, the next permutation of arr = [1,2,3] is [1,3,2].
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.

Given an array of integers numsfind the next permutation of nums.

The replacement must be in place and use only constant extra memory.



def nextPermutation(nums):
    L = len(nums)        
    pivot = -1
    for i in range (L-2, -1, -1):            
        if nums[i] < nums[i+1]:
            pivot = i
            break
           
    if pivot >= 0:
        for j in range (L-1, pivot, -1):            
            if nums[j] > nums[pivot]:
                nums[j], nums[pivot] = nums[pivot], nums[j]
                break

    # reverse, pivot+1-th to end        
    i, j = pivot + 1, L - 1
   
    while i < j:                
        nums[i], nums[j] = nums[j], nums[i]
        i += 1
        j -= 1 

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break