A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi]
, where Li
and Ri
are the x coordinates of the left and right edge of the ith building, respectively, and Hi
is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX
, 0 < Hi ≤ INT_MAX
, and Ri - Li > 0
. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ]
.
The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ]
that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]
.
Notes:
[0, 10000]
.Li
.[...[2 3], [4 5], [7 5], [11 5], [12 7]...]
is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
Credits:
Special thanks to @stellari for adding this problem, creating these two awesome images and all test cases.
class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int, int>> res; int cur=0, cur_X, cur_H =-1, len = buildings.size(); priority_queue< pair<int, int>> liveBlg; // 第一个元素是高度buindings[k][2],第二个元素是结束点的x坐标buildings[k][1] while(cur<len || !liveBlg.empty()) { // 如果是最开始处理建筑,或者出现建筑物不连续的情况(即对于上面第4个建筑和第3个建筑分开的情况) cur_X = liveBlg.empty()? buildings[cur][0]:liveBlg.top().second; // 最高建筑的结束点 if(cur>=len || buildings[cur][0] > cur_X) { //将结束时间小于等于最高建筑结束点的哪些建筑物从优先队列中弹出 while(!liveBlg.empty() && ( liveBlg.top().second <= cur_X) ) liveBlg.pop(); } else { //如果当前遍历到的建筑物在最高的建筑物结束之前开始,那么处理当前的建筑物 cur_X = buildings[cur][0]; while(cur<len && buildings[cur][0]== cur_X) // 处理所有在同一点开始的建筑物 { // just push them in the queue liveBlg.push(make_pair(buildings[cur][2], buildings[cur][1])); cur++; } } cur_H = liveBlg.empty()?0:liveBlg.top().first; // 输出最顶端的建筑物的高度 if(res.empty() || (res.back().second != cur_H) ) res.push_back(make_pair(cur_X, cur_H)); } return res; } };