Leetcode 218 The Skyline Problem

https://leetcode.com/problems/the-skyline-problem/description/

题意,给定一个array的vector, 2,9, 10(代表从2-9这个区间内我有一个10的大楼),我需要求出这个城市的天际线(描边)

buildings = \[2,9,10,3,7,15,5,12,12,15,20,10,19,24,8]

output \[2,10,3,15,7,12,12,0,15,10,20,8,24,0]

首先第一个思想:

我要描边,什么时候会有这个需求?肯定是我的高度发生改变的时候需要记录下来

非常容易想到扫描线算法,确定event上升沿下降沿,并且用一个数据结构去维护此时的最大值,但是这个数据结构还要有一定的快速删除的能力,所以用multiset

cpp 复制代码
class Solution {
public:
    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
        vector<vector<int>> ret;
        vector<pair<int, int>> events;
        for (auto& b : buildings) {
            events.push_back({b[0], -b[2]});
            events.push_back({b[1], b[2]});
        }
        sort(events.begin(), events.end());
        int prevH = 0;
        multiset<int> height;
        height.insert(0);

        for(auto& [x,h]: events) {
            if (h < 0) {
                height.insert(-h);
            } else {
                height.erase(height.find(h));
            }
            int currentH = *height.rbegin();
            if(currentH != prevH) {
                ret.push_back({x,currentH});
                prevH = currentH;
            }
        }
        return ret;
    }
};
相关推荐
星马梦缘6 分钟前
算法设计与分析 作业三 纯答案
算法
不知名的老吴33 分钟前
经典算法题之行星碰撞
数据结构·算法
西安邮电大学39 分钟前
有关数组的经典算法题
java·后端·其他·算法·面试
学Linux的语莫44 分钟前
大模型微调数据集格式详解:Alpaca、ShareGPT、DPO、KTO、预训练数据怎么构建?
人工智能·算法·机器学习·微调格式
wayz111 小时前
Momentum:UO(终极震荡指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
Boom_Shu1 小时前
浅拷贝与深拷贝
开发语言·c++·算法
触底反弹1 小时前
一文彻底搞懂 JavaScript 栈和队列(建议收藏)
javascript·算法·面试
WL学习笔记1 小时前
通讯录(顺序表实现)
c语言·数据结构·算法
Jerryhut2 小时前
opencv对齐算法及其应用
人工智能·opencv·算法
果丁智能2 小时前
智慧校园一卡通深度融合方案:基于超级SIM卡的手机碰一碰智能开锁技术落地实践
数据结构·人工智能·python·科技·算法·智能家居·信息与通信