Python Easy Understand Solution


  • 1

    My idea starts from this example n = 6 and k=5: [1,6,2,5,3,4]
    If k < n-1, I arrange the numbers increasing or decreasing from the k-th number.

    def constructArray(self, n, k):
            l, r, res = 2, n, [1]
            for _ in range(k - 1):
                if len(res) & 1:
                    res.append(r)
                    r -= 1
                else:
                    res.append(l)
                    l += 1
            if len(res) & 1:
                res.extend(range(l, r + 1))
            else:
                res.extend(range(r, l - 1, -1))
            return res

Log in to reply
 

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