forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue-reconstruction-by-height.cpp
57 lines (52 loc) · 1.83 KB
/
queue-reconstruction-by-height.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
54
55
56
57
// Time: O(n * sqrt(n))
// Space: O(n)
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
sort(people.begin(), people.end(),
[](const pair<int, int>& a, pair<int, int>& b) {
return b.first == a.first ? a.second < b.second : b.first < a.first;
});
vector<vector<pair<int, int>>> blocks(1);
for (const auto& p : people) {
auto index = p.second;
int i = 0;
for (; i < blocks.size(); ++i) {
if (index <= blocks[i].size()) {
break;
}
index -= blocks[i].size();
}
blocks[i].emplace(blocks[i].begin() + index, p);
if (blocks[i].size() * blocks[i].size() > people.size()) {
blocks.emplace(blocks.begin() + i + 1,
blocks[i].begin() + blocks[i].size() / 2,
blocks[i].end());
blocks[i].erase(blocks[i].begin() + blocks[i].size() / 2, blocks[i].end());
}
}
vector<pair<int, int>> result;
for (const auto& block : blocks) {
for (const auto& p : block) {
result.emplace_back(p);
}
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
sort(people.begin(), people.end(),
[](const pair<int, int>& a, pair<int, int>& b) {
return b.first == a.first ? a.second < b.second : b.first < a.first;
});
vector<pair<int, int>> result;
for (const auto& p : people) {
result.emplace(result.begin() + p.second, p);
}
return result;
}
};