2 methods in python, beat 95.49%


  • 0
    F

    first, reverse list in place, easy to code but slow, takes about 675ms:

        def constructArray(self, n, k):
            result = range(1, n + 1)
            for i in range(1, k):
                result[i:] = result[:i - 1:-1]
            return result
    

    second, use deque, takes about 85ms, beat 95%:

        def constructArray2(self, n, k):
            from collections import deque
            src = deque(range(1, n + 1))
            dst = [src.pop() if i % 2 else src.popleft() for i in range(k)]
            if k % 2 == 0:
                src.reverse()
            dst.extend(src)
            return dst

Log in to reply
 

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