1. 漂亮数组
对于某些固定的 N
,如果数组 A
是整数 1, 2, ..., N
组成的排列,使得:
对于每个 i < j
,都不存在 k
满足 i < k < j
使得 A[k] * 2 = A[i] + A[j]
。
那么数组 A
是漂亮数组。
给定 N
,返回任意漂亮数组 A
(保证存在一个)。
Example 1
输入:4
输出:[2,1,4,3]
Example 2
输入:5
输出:[3,1,2,5,4]
代码
class Solution {
private:
unordered_map<int, vector<int>> memo;
vector<int> divide(int n){
if(memo.count(n)) return memo[n];
vector<int> ans(n);
if(n==1){
ans[0]=1;
}else{
int t=0;
for(int x:divide((n+1)>>1)) ans[t++]=(x<<1)-1;
for(int x:divide(n>>1)) ans[t++]=x<<1;
}
memo[n]=ans;
return ans;
}
public:
vector<int> beautifulArray(int n) {
return divide(n);
}
};