Loading...https://leetcode.com/problems/beautiful-array/
题目描述
An array nums
of length n
is beautiful if:
nums
is a permutation of the integers in the range[1, n]
.- For every
0 <= i < j < n
, there is no indexk
withi < k < j
where2 * nums[k] == nums[i] + nums[j]
.
Given the integer n
, return any beautiful array nums
of length n
. There will be at least one valid answer for the given n
.
Example 1:
Input: n = 4 Output: [2,1,4,3]
Example 2:
Input: n = 5 Output: [3,1,2,5,4]
Constraints:
1 <= n <= 1000
解题思路
【C++】
class Solution {
public:
vector<int> beautifulArray(int n) {
if (n == 1) return {1};
auto left = beautifulArray(n / 2);
auto right = beautifulArray(n - (n / 2));
vector<int> res;
for (auto l : left) {res.push_back(l * 2);}
for (auto r : right) {res.push_back(r * 2 - 1);}
return res;
}
};
【Java】
class Solution {
public int[] beautifulArray(int n) {
int[] answer = new int[n];
if (n == 1) {
answer[0] = 1;
return answer;
}
int[] left = beautifulArray(n/2);
int[] right = beautifulArray((n+1)/2);
for(int i=0; i<left.length; i++) {
answer[i] = left[i] * 2;
}
for (int i=left.length; i<n; i++) {
answer[i] = right[i-left.length] * 2 - 1;
}
return answer;
}
}