667. Beautiful Arrangement II

Information

  • Diffculty: Medium

  • Created: 2019-09-05 22:39:03

  • Last Motified: 2019-09-05 22:39:03

Solution

class Solution:
    def constructArray(self, n: int, k: int) -> List[int]:
        ans = [1]
        i = 2
        j = n
        while k != 1:
            if len(ans) % 2 == 0:
                ans.append(i)
                i += 1
            else:
                ans.append(j)
                j -= 1
            k -= 1
        if len(ans) % 2 == 0:
            ans.extend(list(range(j, i - 1, -1)))
        else:
            ans.extend(list(range(i, j + 1)))
        return ans