1. Description of the problem
Notes:
- The number of buildings in the all input list is guaranteed to being in the range [0, 10000].
- The input list is already sorted in ascending order by the left X position Li.
- The output list must is sorted by the X position.
- There must is no consecutive horizontal lines of equal height in the output skyline. For instance, [... [2 3], [4 5], [7 5], [11 5], [12 7] ...] is not acceptable; The three lines of height 5 should is merged into one in the final output as such: [... [2 3], [4 5], [12 7], ...]
2. Methods and Ideas
The idea is: Left and right node +multiset
First, all the buildings are divided into the structure where the left and right nodes (the x-coordinate, the high) and the (rvalue-coordinate, high) are stored separately vector<pair<int,int>>
. Here in order to separate left and right processing, do node high with negative representation.
Then, the node coordinates are sorted by x-coordinate.
After that, loop through the vector of the nodes, insert the height of the node into the multiset, and determine whether the previous height is the same as the current, and if not, save the current and x coordinates.
The idea borrowed from Eason Liu's technical blog, here Express thanks!
classSolution { Public: vector<pair<int, int>> Getskyline ( vector<vector<int>>& buildings) {intI,j,pre,cur; vector<pair<int,int>> re,height; multiset<int>Heap for(i =0; I < buildings.size (); i++) {Height.push_back (pair<int,int> (buildings[i][0],-buildings[i][2])); Height.push_back (pair<int,int> (buildings[i][1], buildings[i][2])); } sort (Height.begin (), Height.end ()); Heap.insert (0); Pre =0; Cur =0; for(i =0; I < height.size (); i++) {if(Height[i].second <0) Heap.insert (-height[i].second);ElseHeap.erase (Heap.find (Height[i].second)); cur = *heap.rbegin ();The maximum value of the last element in the//multiset, height if(cur! = Pre) {Re.push_back (pair<int,int> (height[i].first,cur)); Pre = cur; } }returnRe }};
Leetcode 218 The Skyline problem