In place Python solution


  • 0
    G
    class Solution:
        # @param num, a list of integer
        # @return nothing (void), do not return anything, modify num in-place instead.
        # 1:23
        def nextPermutation(self, num):
            for i in range(len(num) - 2, -1, -1):
                for j in range(len(num) - 1, i, -1):
                    if num[i] < num[j]:
                        num[i], num[j] = num[j], num[i]
                        num[i+1:] = num[i+1:][::-1]
                        return
            
            num.reverse()

  • 0
    F

    ...which, unfortunately, has quadratic running time in the worst case (e.g. if you already have the last permutation)


Log in to reply
 

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