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;
    }
};
相关推荐
MATLAB代码顾问18 小时前
粒子群优化算法(PSO)原理与Python高级实现
开发语言·python·算法
Epiphany.55618 小时前
连通块的遍历
c++·算法·蓝桥杯
alxraves18 小时前
超声诊断图像的关键算法概述
算法·安全·健康医疗·制造·信号处理
mask哥18 小时前
15种算法模式java实现详解
java·算法·力扣
若尘79718 小时前
数学idea的重构
算法·职场和发展·机器人
思茂信息18 小时前
CST可重构雷达吸波器设计与仿真
网络·算法·平面·智能手机·重构·cst·电磁仿
游乐码18 小时前
c#插入排序
数据结构·算法·排序算法
乐迪信息18 小时前
乐迪信息:AI防爆摄像机,船舶偏航逆行算法实时告警零漏检
大数据·人工智能·物联网·算法·机器学习·计算机视觉·目标跟踪
昵称小白19 小时前
图论专题(上)
算法·深度优先·图论
大大杰哥19 小时前
leetcode hot100(2)双指针,滑动窗口
数据结构·算法·leetcode