【leetcode】667. Beautiful Arrangement II
阿新 • • 發佈:2018-12-09
題目如下:
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