Approach
Sorting and greedy selection
For The Skyline Problem, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 41 lines of C++ from the credited upstream file 218-2.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {4 vector<vector<int>> ans;5 vector<vector<int>> events; 6 7 for (const vector<int>& b : buildings) {8 events.push_back({b[0], b[2]});9 events.push_back({b[1], -b[2]}); 10 }11 12 ranges::sort(events, ranges::less{}, [](const vector<int>& event) {13 return pair<int, int>{event[0], -event[1]};14 });15 16 for (const vector<int>& event : events) {17 const int x = event[0];18 const int h = abs(event[1]);19 const int isEntering = event[1] > 0;20 if (isEntering) {21 if (h > maxHeight())22 ans.push_back({x, h});23 set.insert(h);24 } else {25 set.erase(set.equal_range(h).first);26 if (h > maxHeight())27 ans.push_back({x, maxHeight()});28 }29 }30 31 return ans;32 }33 34 private:35 multiset<int> set;36 37 int maxHeight() const {38 return set.empty() ? 0 : *set.rbegin();39 }40};41