-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathThe_Skyline_Problem.cpp
78 lines (72 loc) · 2.29 KB
/
The_Skyline_Problem.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Runtime beats 100% of cpp submissions with huge margin
class Solution {
class edge {
public:
int x;
int height;
bool isLeft;
edge(){}
edge(int a, int b, bool c):
x(a), height(b), isLeft(c) {
}
};
static bool compare(edge const& lhs, edge const& rhs) {
if(lhs.x != rhs.x) {
return lhs.x < rhs.x;
}
if(lhs.isLeft and rhs.isLeft) {
return lhs.height > rhs.height;
}
if(!lhs.isLeft and !rhs.isLeft) {
return lhs.height < rhs.height;
}
return lhs.isLeft;
}
public:
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
vector<pair<int, int>> result;
if(buildings.empty()) return result;
int n = (int)buildings.size();
multiset<int> H;
vector<edge> edges;
for(int i = 0; i < n; ++i) {
edges.push_back(edge(buildings[i][0], buildings[i][2], true));
edges.push_back(edge(buildings[i][1], buildings[i][2], false));
}
sort(edges.begin(), edges.end(), compare);
// solution #1
/*
for(int i = 0; i < (int)edges.size(); ++i) {
if(edges[i].isLeft) {
if(H.empty() or edges[i].height > *(--H.end())) {
result.push_back({edges[i].x, edges[i].height});
}
H.insert(edges[i].height);
} else {
H.erase(H.find(edges[i].height));
if(H.empty()) {
result.push_back({edges[i].x, 0});
}
else if(edges[i].height > *(--H.end())) {
result.push_back({edges[i].x, *(--H.end())});
}
}
}
*/
// solution #2
int prev = 0;
for(int i = 0; i < (int)edges.size(); ++i) {
if(edges[i].isLeft) {
H.insert(edges[i].height);
} else {
H.erase(H.find(edges[i].height));
}
int curr = (H.empty() ? 0 : *(--H.end()));
if(curr != prev) {
result.push_back({edges[i].x, curr});
prev = curr;
}
}
return result;
}
};