3 Lines Python


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

    Example: n = 7
    k = 1, 1234567
    k = 2, 1765432
    k = 3, 1723456
    ....


  • 0
    J

    It's very elegant and pythonic!! :)

    One question is, there is some concern over redundancy and efficiency... When k=3, the segment "23456" is reversed to be "65432" and reversed back to "23456".


Log in to reply
 

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