Skip to content

Commit 6e8e16b

Browse files
committed
SkylineProblem Solved Using Multiset and Sorting
1 parent d74a84d commit 6e8e16b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

leetcode/SkylineProblem.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// 218. The Skyline Problem
2+
// Ques Topic : Ordered Set, Hashmaps and Heaps, Sorting.
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
class Solution {
7+
public:
8+
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
9+
// use walls to record buildings; left x is an insertion event, and right x is a deletion event
10+
vector<pair<int, int>>xaxis; // first: x, second: height
11+
vector<vector<int>>ans;
12+
for (auto b : buildings) {
13+
// let left x has negative height to ensure left x goes to multiset first if with same 'x' as right x // add before removing is imp in case of same right x of one building and left x of other building
14+
xaxis.push_back(make_pair(b[0], -b[2]));
15+
xaxis.push_back(make_pair(b[1], b[2]));
16+
}
17+
sort(xaxis.begin(), xaxis.end()); // sort walls
18+
multiset<int>leftxHeights = {0};// keep left x heights sorted; dummy'0'for convenience
19+
int mhabtpi = 0; // current max height among leftxHeights
20+
for (auto xh : xaxis) {
21+
if (xh.second < 0) { // it's a left x, insert the height
22+
leftxHeights.insert(-xh.second);
23+
}
24+
else { // it's a right x, delete the height
25+
leftxHeights.erase(leftxHeights.find(xh.second));
26+
}
27+
28+
if (*leftxHeights.rbegin() != mhabtpi) { // mark a skyline point
29+
ans.push_back({xh.first,mhabtpi = *leftxHeights.rbegin()});
30+
}
31+
}
32+
return ans;
33+
}
34+
};

0 commit comments

Comments
 (0)