Python, swap and pop, worst case O(n^2)


  • 0
    class Solution(object):
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            A, F = ['1'], 1
            for i in xrange(1, n):
                A.append(str(i + 1))
                F *= i
            
            k -= 1
            i = 0
            while k:
                o, k = divmod(k, F)
                A.insert(i, A.pop(o + i))
                i += 1
                F /= n - i
            
            return ''.join(A)
    

Log in to reply
 

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