Python solution O(n) 84ms


  • 0
    A
    class Solution:
        # @param {integer[]} nums
        # @return {void} Do not return anything, modify nums in-place instead.
        def nextPermutation(self, nums):
            if not nums or len(nums) <= 1:
                return
            for i in range(len(nums)-1,0,-1):
                if nums[i-1] < nums[i]:
                    j = i-1
                    while i < len(nums) and nums[i] > nums[j]:
                        i += 1
                    i -= 1
                    nums[j],nums[i] = nums[i],nums[j]
                    j += 1
                    nums[j:] = nums[j:][::-1]
                    return
            nums[::] = nums[::-1]

  • 0
    S

    Does list slicing use extra memory?


  • 0

    Yes, it does.


Log in to reply
 

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