LeetCode 667 Beautiful Arrangement II (Python)

Posted by 小明MaxMing on April 14, 2021

题目

Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:

Suppose this list is answer = [a1, a2, a3, … , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, … , |an-1 - an|] has exactly k distinct integers. Return the list answer. If there multiple valid answers, return any of them.

解题思路

直接进行构造,先把1到n-k放到结果里,之后每个数相差从k到1

代码

class Solution:
    def constructArray(self, n: int, k: int) -> List[int]:
        res = list(range(1, n - k + 1))
        f, d = 1, k
        for i in range(k):
            res.append(res[-1] + f * d)
            f = -f
            d -= 1
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅