forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
53 lines (38 loc) · 1.02 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/// Source : https://leetcode.com/problems/beautiful-array/
/// Author : liuyubobobo
/// Time : 2018-10-30
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Divide and Conquer
/// The key observation is that {odd number, x, even number} satisfies the property forever!
///
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
public:
vector<int> beautifulArray(int N) {
if(N == 0) return {};
if(N == 1) return {1};
if(N == 2) return {1, 2};
vector<int> res;
int odd = (N + 1) / 2, even = N - odd;
vector<int> left = beautifulArray(odd);
for(int e: left)
res.push_back(2 * e - 1);
vector<int> right = beautifulArray(even);
for(int e: right)
res.push_back(2 * e);
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
print_vec(Solution().beautifulArray(5));
return 0;
}