Python Solution with explanation.


  • 0

    Let's look inside this problem, the requirement can be reduced into two different parts:

    1. N numbers; 2. K distinct distances.

    As long as realizing this, the solution is almost there.

    Two steps:

    step 1: I call it "vibration", that is taking the start and end number periodically
    for the purpose of unique distances.

    step 2, enum the remaining nums increasingly or decreasingly to fulfill the requirement of
    this problem.

    class Solution(object):
        def constructArray(self, n, k):
            ans = []
            left, right = 1, n
            idxLeft = 0
            while k > 1:
                if len(ans) % 2 == 1:
                    ans.append(right)
                    right -= 1
                    idxLeft = 0
                else:
                    ans.append(left)
                    left += 1
                    idxLeft = 1
                k -= 1
            while right >= left:
                if idxLeft == 1:
                    ans.append(right)
                    right -= 1
                else:
                    ans.append(left)
                    left += 1
            return ans
    

Log in to reply
 

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