【leetcode】667. Beautiful Arrangement II
题目如下:
Given two integers
n
andk
, you need to construct a list which containsn
different positive integers ranging from1
ton
and obeys the following requirement:
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactlyk
distinct integers.If there are multiple answers, print any of them.
Example 1:
Input: n = 3, k = 1 Output: [1, 2, 3] Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
Example 2:
Input: n = 3, k = 2 Output: [1, 3, 2] Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.
Note:
- The
n
andk
are in the range 1 <= k < n <= 104.
解题思路:感觉自己对“给定一个条件,输出对应排列”这一类型的题目比较没有思路。本题的解法我也是想了很久才想出来。以[1,2,3,4,5,6]为例,当前k是等于1的;假设要k=2,只需要把6插入到头部[6,1,2,3,4,5]即可。而如果要k=3,那么把6插入到1的后面,变成[1,6,2,3,4,5]。接下来就是递推了,记插入6的位置为inx,要使得k=4,只要在k=2的基础上把最后一个元素插入到inx+2的位置;同理,如果是k=5,就在k=3的基础上操作。
代码如下:
class Solution(object): def constructArray(self, n, k): """ :type n: int :type k: int :rtype: List[int] """ res = [i for i in range(1,n+1)] inx = 0 if k % 2 == 1: inx = 1 else: res.insert(0, res.pop(-1)) k -= 1 inx += 2 while k > 1: res.insert(inx,res.pop(-1)) inx += 2 k -= 2 return res