simple python solution o(n)


  • 0

    if k == n - 1 and n == 6 the solution would be
    6 _ 5 _ 4
    _ 1 _ 2 _ 3 (insert above)

    ans = [6,1,5,2,4,3]

    if k < n - 1, then just process first n number.

    class Solution(object):
        def constructArray(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: List[int]
            """
            
            p = [i for i in range(1, n + 1)]
            if k == 1:
                return p
            
            cc = k + 1
            dd = 1
            
            for i in range(k + 1):
                if i % 2 == 0:
                    p[i] = cc
                    cc -= 1
                else:
                    p[i] = dd
                    dd += 1
            return p
                    
    

Log in to reply
 

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