multimap, multiset, map, set的底层实现都是红黑树,减少查询时间的同时还可以进行排序,相对于优先队列的优点是可以修改元素,其实优先队列也可以修改元素,只不过修改后需要重新排列一次,discuss中也有很多人用优先队列的,也有一些人用优先队列加哈希表进一步优化时间复杂度
这里对输入的vector做了预处理,便于解析左右节点,对multiset<int> m进行维护
class Solution {
public:
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
vector<pair<int, int>> edges;
int left, right, height;
for (int i = 0; i<buildings.size(); i++) {
left = buildings[i][0];
right = buildings[i][1];
height = buildings[i][2];
/*** make sure : for the same left point we use the bigger height ***/
edges.push_back(make_pair(left, -height));
edges.push_back(make_pair(right, height));
}
sort(edges.begin(), edges.end());
vector<pair<int, int>> result;
/*** use the multiset to store the max height util current pos ***/
multiset<int> m;
/*** left most height ***/
m.insert(0);
int pre = 0, cur = 0;
for (int i = 0; i<edges.size(); i++) {
pair<int, int> e = edges[i];
if (e.second < 0) //如果是线段的左端点
m.insert(-e.second);//把height插入到multiset中
else//如果是线段的右端点
m.erase(m.find(e.second));//删除掉multiset中的对应height
cur = *(m.rbegin());
if (cur != pre) {//如果当前位置的最大height和当前位置的height不一样,就保存最大height
result.push_back(make_pair(e.first, cur));
pre = cur;
}
}
return result;
}
};