您的位置:首页 > 其它

Leetcode 218 The Skyline Problem

2017-06-23 10:53 363 查看

1. 问题描写叙述

  



Notes:

The number of buildings in any input list is guaranteed to be in the range [0, 10000].

The input list is already sorted in ascending order by the left x position Li.

The output list must be sorted by the x position.

There must be 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 be merged into one in the final output as such: […[2 3], [4 5], [12 7], …]

2. 方法与思路

  总得思路是:左右节点+multiset

  首先,将全部的buildings分为左右节点(左x坐标,高)和(右x坐标,高)分别存储到
vector<pair<int,int>>
的结构中。这里为了将左右分开处理,做节点的高用负数表示。

  然后,将节点坐标按x坐标排序。

  之后,循环遍历节点vector。将节点的高插入到multiset中。并推断之前的高是否与当前一样。若不一样则保存当前高度和x坐标。


思路借鉴了Eason Liu的技术博客,这里表示感谢!



class Solution {
public:
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
int i,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);
else
heap.erase(heap.find(height[i].second));

cur = *heap.rbegin();//multiset中最后一个元素。height的最大值
if(cur != pre)
{
re.push_back(pair<int,int>(height[i].first,cur));
pre = cur;
}
}

return re;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: