試題
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. (It is guaranteed that one exists.)
Example 1:
Input: 4
Output: [2,1,4,3]
Example 2:
Input: 5
Output: [3,1,2,5,4]
代碼
分治思想;
class Solution {
Map<Integer, int[]> memo;
public int[] beautifulArray(int N) {
memo = new HashMap();
return f(N);
}
//完美序列可以通過映射得到新的完美序列:
//2*(a[k] + x) != (a[i] + x) + (a[j] + x) ,當序列中元素加上x時,新的序列仍然滿足完美序列
//2*(a[k]*y) != a[i]*y + a[j]*y ,當序列中元素乘以y時,新的序列仍然滿足完美序列
public int[] f(int N){
if(memo.containsKey(N)) return memo.get(N);
int[] tmp = new int[N];
if(N == 1){
tmp[0] = 1; //最簡單的完美序列N=1時的[1]
}else{
int t = 0;
//1、假設f((N+1)/2)是完美序列,那麼對其乘2減1後仍然是完美序列,
for(int x : f((N+1)/2)) //對於1~N,有(N+1)/2個奇數,使用1~(N+1)/2映射到1-N中奇數
tmp[t++] = 2 * x - 1;
//2、假設f(N/2)是完美序列,那麼對其乘2後仍然是完美序列
for(int x : f(N/2)) //對於1-N,有N/2個偶數,使用2N映射到1-N中偶數
tmp[t++] = 2 * x;
//3、當將奇數和偶數拼接起來後,因爲奇數部分和偶數部分已經滿足,那麼只需要考慮奇偶合並起來的情況,當i在奇數部分而j在偶數部分時顯然a[i](奇數) + a[j](偶數) != a[k](偶數)。所以拼接起來的序列仍然是完美序列。
}
memo.put(N, tmp);
return tmp;
}
}