932. Beautiful Array
阿新 • • 發佈:2018-11-18
For some fixed N
, an array A
is beautiful if it is a permutation of the integers 1, 2, ..., N
, such that:
For every i < j
, there is no k
with i < k < j
such that A[k] * 2 = A[i] + A[j]
.
Given N
, return any beautiful array A
Example 1:
Input: 4
Output: [2,1,4,3]
Example 2:
Input: 5
Output: [3,1,2,5,4]
Note:
1 <= N <= 1000
思路:
比賽想到的時候是分成2部分,前面一部分,後面一部分,然後儘量2者組合不會有問題,這樣的話就可以分治到2邊,偶數還好辦,但是奇數就卡住了。
後面看題解:不要分前半部分後半部分,直接分奇數偶數
One way is to divide into [1, N / 2] and [N / 2 + 1, N]. But it will cause problems when we merge them.
Another way is to divide into odds part and evens part. So there is no k
with A[k] * 2 = odd + even
需要注意的是:對一個符合條件的數組裡面所有的數進行同一個操作,仍然是滿足條件的。這也是為什麼能分治的條件
class Solution: def beautifulArray(self, N): """ :type N: int :rtype: List[int] """ if N==1: return [1] l=self.beautifulArray(N//2) r=self.beautifulArray(N-N//2) return [i*2 for i in l]+[i*2-1 for i in r]