|
43 | 43 |
|
44 | 44 | <!-- 这里可写通用的实现逻辑 -->
|
45 | 45 |
|
| 46 | +**方法一:分治** |
| 47 | + |
| 48 | +根据题意,漂亮数组 $A$ 需要满足对于任意 $i<k<j$, $A_k*2 \neq A_i+A_j$。 |
| 49 | + |
| 50 | +我们可以发现,不等式左侧一定是偶数,那么我们只要保证不等式右侧 $A_i$ 和 $A_j$ 分别是一奇一偶,那么不等式就恒成立。 |
| 51 | + |
| 52 | +利用分治,我们将 $n$ 缩小规模为原来的一半,递归调用,可以得到两个漂亮数组 $left$, $right$。我们将 $left$ 中每个元素 $x_i$ 变为 $x_i*2-1$ 可以得到一个奇数数组;将 $right$ 中每个元素 $x_i$ 变为 $x_i*2$,可以得到一个偶数数组。这两个数组仍然是漂亮数组。 |
| 53 | + |
| 54 | +> 基于一个性质,将漂亮数组中的每个元素 $x_i$ 变换为 $kx_i+b$,得到的数组仍然是漂亮数组。 |
| 55 | +
|
| 56 | +将这两个漂亮数组合并在一起,由于满足一奇一偶,那么合并后的数组也是漂亮数组,从而得到了答案。 |
| 57 | + |
| 58 | +时间复杂度 $O(nlogn)$。 |
| 59 | + |
46 | 60 | <!-- tabs:start -->
|
47 | 61 |
|
48 | 62 | ### **Python3**
|
49 | 63 |
|
50 | 64 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
51 | 65 |
|
52 | 66 | ```python
|
53 |
| - |
| 67 | +class Solution: |
| 68 | + def beautifulArray(self, n: int) -> List[int]: |
| 69 | + if n == 1: |
| 70 | + return [1] |
| 71 | + left = self.beautifulArray((n + 1) >> 1) |
| 72 | + right = self.beautifulArray(n >> 1) |
| 73 | + left = [x * 2 - 1 for x in left] |
| 74 | + right = [x * 2 for x in right] |
| 75 | + return left + right |
54 | 76 | ```
|
55 | 77 |
|
56 | 78 | ### **Java**
|
57 | 79 |
|
58 | 80 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
59 | 81 |
|
60 | 82 | ```java
|
| 83 | +class Solution { |
| 84 | + public int[] beautifulArray(int n) { |
| 85 | + if (n == 1) { |
| 86 | + return new int[]{1}; |
| 87 | + } |
| 88 | + int[] left = beautifulArray((n + 1) >> 1); |
| 89 | + int[] right = beautifulArray(n >> 1); |
| 90 | + int[] ans = new int[n]; |
| 91 | + int i = 0; |
| 92 | + for (int x : left) { |
| 93 | + ans[i++] = x * 2 - 1; |
| 94 | + } |
| 95 | + for (int x : right) { |
| 96 | + ans[i++] = x * 2; |
| 97 | + } |
| 98 | + return ans; |
| 99 | + } |
| 100 | +} |
| 101 | +``` |
| 102 | + |
| 103 | +### **C++** |
| 104 | + |
| 105 | +```cpp |
| 106 | +class Solution { |
| 107 | +public: |
| 108 | + vector<int> beautifulArray(int n) { |
| 109 | + if (n == 1) return {1}; |
| 110 | + vector<int> left = beautifulArray((n + 1) >> 1); |
| 111 | + vector<int> right = beautifulArray(n >> 1); |
| 112 | + vector<int> ans(n); |
| 113 | + int i = 0; |
| 114 | + for (int& x : left) ans[i++] = x * 2 - 1; |
| 115 | + for (int& x : right) ans[i++] = x * 2; |
| 116 | + return ans; |
| 117 | + } |
| 118 | +}; |
| 119 | +``` |
61 | 120 |
|
| 121 | +### **Go** |
| 122 | +
|
| 123 | +```go |
| 124 | +func beautifulArray(n int) []int { |
| 125 | + if n == 1 { |
| 126 | + return []int{1} |
| 127 | + } |
| 128 | + left := beautifulArray((n + 1) >> 1) |
| 129 | + right := beautifulArray(n >> 1) |
| 130 | + var ans []int |
| 131 | + for _, x := range left { |
| 132 | + ans = append(ans, x*2-1) |
| 133 | + } |
| 134 | + for _, x := range right { |
| 135 | + ans = append(ans, x*2) |
| 136 | + } |
| 137 | + return ans |
| 138 | +} |
62 | 139 | ```
|
63 | 140 |
|
64 | 141 | ### **...**
|
|
0 commit comments