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;
    }
};
相关推荐
珠海西格电力2 小时前
数据采集与治理:零碳园区管理系统的 “生命线”
大数据·人工智能·算法·架构·能源
●VON2 小时前
HarmonyKit | 鸿蒙新特性:router 导航 API 从 pushUrl 到 UIContext 的演进
算法·华为·交互·harmonyos
星释2 小时前
鸿蒙智能体开发实战:31.鸿蒙壁纸大师 - 环境搭建与基础配置
算法·华为·ai·harmonyos·鸿蒙
ysa0510303 小时前
【板子】树上启发式合并
数据结构·c++·笔记·算法
学究天人3 小时前
数学公理体系大全:第一章 命题逻辑:真值之舞
人工智能·算法·机器学习·数学建模·动态规划·图论·抽象代数
小O的算法实验室3 小时前
2025年Neurocomputing,基于LLM的进化优化器:结合精英策略推理
算法
2301_800256114 小时前
数据结构基础期末复习例题
数据结构·算法
变量未定义~4 小时前
单调栈-四元组问题
数据结构·算法
冷小鱼5 小时前
AI Agent 核心算法:任务规划(Planning)的深度技术解析
人工智能·算法·planning
退休倒计时5 小时前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript