Python learnt from some one in the forum with explanation

  • 0

    '''class Solution:
    # @param {integer[]} nums
    # @return {void} Do not return anything, modify nums in-place instead.
    def nextPermutation(self, nums):
    if len(nums) <= 1:
    for i in range(len(nums)-1,0,-1):
    # find the right first number that is not descendent and mark as J(small value like 1 in (1,3,2))
    if nums[i-1] < nums[i]:
    j = i - 1
    # now find the the one who is larger than J in the right side for swap purpose (like 2 in (1,3,2))
    while i < len(nums) and nums[i] > nums[j]:
    i += 1
    i -= 1
    nums[i], nums[j] = nums[j], nums[i]
    j += 1
    # reverse everything right to J before they are descendent already after the change (before reverse: (2,3,1) turn to be (3,1,2))
    nums[j:] = nums[j:][::-1]
    # if nothing is done before, then it must be the largest one already, consider reverse all for the smallest value.
    nums[::] = nums[::-1]

Log in to reply

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