主页有其他数据结构内容(持续更新中)
难度:Hard
即使是用了优先队列,需要考虑的细节还是很多
名副其实的Hard题!
代码:
class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<vector<int>> ans;
priority_queue<pair<int, int>> max_heap;
int i = 0, len = buildings.size();
int cur_x, cur_h;
while (i < len || !max_heap.empty()) {
// 如果最高的矩形和当前矩形有重合,处理左端点
// 当前矩形的左端和最高矩形的右端比较,如果小于说明有重合
// 只需要和最高矩形比较,其他矮的不用管
if (max_heap.empty() || i < len && buildings[i][0] <= max_heap.top().second) {
cur_x = buildings[i][0];
//相同的左端点全部入队,选择最高高度
while (i < len && cur_x == buildings[i][0]) {
max_heap.emplace(buildings[i][2], buildings[i][1]); // 插入[当前矩形高度, 当前矩形右端]
//遍历矩阵
++i;
}
}
else {
//如果最高的矩形和当前矩形不重合,处理之前重合矩形的右端点
cur_x = max_heap.top().second;
//选择其右侧重合的矩形(不包括本矩形)最高高度
while (!max_heap.empty() && cur_x >= max_heap.top().second) { // 这一步的循环,目的是找出有重合的矩形
max_heap.pop();
}
}
cur_h = (max_heap.empty()) ? 0 : max_heap.top().first;
if (ans.empty() || cur_h != ans.back()[1]) {
ans.push_back({cur_x, cur_h});
}
}
return ans;
}
};