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;
    }
};
相关推荐
橘颂TA1 分钟前
【剑斩OFFER】算法的暴力美学——力扣 43 题:字符串相乘
数据结构·算法·leetcode·职场和发展·哈希算法·结构与算法
海边的Kurisu1 分钟前
代码随想录算法第六十四天| To Be Continued
算法
less is more_09303 分钟前
文献学习——极端高温灾害下电缆型配电网韧性提升策略研究
笔记·学习·算法
小芒果_013 分钟前
P8662 [蓝桥杯 2018 省 AB] 全球变暖
c++·算法·蓝桥杯·信息学奥赛
漫随流水8 分钟前
leetcode算法(199.二叉树的右视图)
数据结构·算法·leetcode·二叉树
Vin0sen9 分钟前
leetcode 高频SQL50题
数据库·leetcode
jghhh0110 分钟前
自适应信号时频处理方法MATLAB实现(适用于非线性非平稳信号)
开发语言·算法·matlab
信奥卷王11 分钟前
2025年12月GESPC++一级真题解析(含视频)
算法
曹自标19 分钟前
workflow 拓扑排序算法
windows·算法·排序算法
wen__xvn21 分钟前
代码随想录算法训练营DAY8第四章 字符串part01
算法