C like in place python code, 65ms (need more chars)


  • 0
    H

    Not sure why the other solutions are so hard to understand. Here is mine:

    def nextPermutation(self, num):
        n = len(num) - 1
        while n > 0 and num[n] <= num[n - 1]:
            n -= 1
            
        if n > 0:
            m = len(num) - 1
            while m >= n:
                if num[m] > num[n-1]:
                    num[m], num[n -1] = num[n-1], num[m]
                    break
                m -= 1
            
        k = len(num) -1
        while n < k:
            num[n], num[k] = num[k], num[n]
            n += 1
            k -= 1

Log in to reply
 

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