Skip to content

Commit 0cd785e

Browse files
authored
Create The Skyline Problem
1 parent 10a0de1 commit 0cd785e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

The Skyline Problem

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
4+
int edge_idx = 0;
5+
vector<pair<int, int>> edges;
6+
priority_queue<pair<int, int>> pq;
7+
vector<vector<int>> skyline;
8+
9+
for (int i = 0; i < buildings.size(); ++i) {
10+
const auto &b = buildings[i];
11+
edges.emplace_back(b[0], i);
12+
edges.emplace_back(b[1], i);
13+
}
14+
15+
std::sort(edges.begin(), edges.end());
16+
17+
while (edge_idx < edges.size()) {
18+
int curr_height;
19+
const auto &[curr_x, _] = edges[edge_idx];
20+
while (edge_idx < edges.size() &&
21+
curr_x == edges[edge_idx].first) {
22+
const auto &[_, building_idx] = edges[edge_idx];
23+
const auto &b = buildings[building_idx];
24+
if (b[0] == curr_x)
25+
pq.emplace(b[2], b[1]);
26+
++edge_idx;
27+
}
28+
while (!pq.empty() && pq.top().second <= curr_x)
29+
pq.pop();
30+
curr_height = pq.empty() ? 0 : pq.top().first;
31+
if (skyline.empty() || skyline.back()[1] != curr_height)
32+
skyline.push_back({curr_x, curr_height});
33+
}
34+
return skyline;
35+
}
36+
};

0 commit comments

Comments
 (0)