The key idea is to recursively build a beautiful array by separating numbers into odds and evens. By ensuring that all odd numbers are grouped together and all even numbers are grouped together, we avoid creating any triplet (i, k, j) where 2 * nums[k] == nums[i] + nums[j]. This works because the sum of two odd or two even numbers is always even, but the sum of an odd and an even is odd, so their average is never an integer in the other group.
classSolution {
publicint[]beautifulArray(int n) {
if (n == 1) returnnewint[]{1};
int[] odd = beautifulArray((n + 1) / 2);
int[] even = beautifulArray(n / 2);
int[] ans =newint[n];
int idx = 0;
for (int x : odd) ans[idx++]= 2 * x - 1;
for (int x : even) ans[idx++]= 2 * x;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funbeautifulArray(n: Int): IntArray {
if (n ==1) return intArrayOf(1)
val odd = beautifulArray((n + 1) / 2)
val even = beautifulArray(n / 2)
val ans = IntArray(n)
var idx = 0for (x in odd) ans[idx++] = 2 * x - 1for (x in even) ans[idx++] = 2 * x
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defbeautifulArray(self, n: int) -> list[int]:
if n ==1:
return [1]
odd = self.beautifulArray((n +1) //2)
even = self.beautifulArray(n //2)
ans: list[int] = [2* x -1for x in odd] + [2* x for x in even]
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnbeautiful_array(n: i32) -> Vec<i32> {
if n ==1 {
returnvec![1];
}
let odd = Self::beautiful_array((n +1) /2);
let even = Self::beautiful_array(n /2);
letmut ans = Vec::with_capacity(n asusize);
for&x in&odd {
ans.push(2* x -1);
}
for&x in&even {
ans.push(2* x);
}
ans
}
}