栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode 218.天际线问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode 218.天际线问题

主页有其他数据结构内容(持续更新中)

难度:Hard

即使是用了优先队列,需要考虑的细节还是很多
名副其实的Hard题!

代码:
class Solution {
public:
    vector> getSkyline(vector>& buildings) {
        vector> ans;
        priority_queue> 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; 
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/917423.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号