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;
    }
};
相关推荐
__AtYou__15 分钟前
Golang | Leetcode Golang题解之第451题根据字符出现频率排序
leetcode·golang·题解
IT德1 小时前
数组增删改查操作
数据结构·算法
文sir.2 小时前
【leetcode】 45.跳跃游戏 ||
c语言·算法·leetcode
转调2 小时前
每日一练:零钱兑换
开发语言·c++·leetcode
bobostudio19952 小时前
TypeScript 算法手册【快速排序】
前端·javascript·算法·typescript
小小工匠2 小时前
加密与安全_TOTP 一次性密码生成算法
算法·安全·totp
yttandb3 小时前
《重生到现代之从零开始的C语言生活》—— 内存函数
c语言·算法·生活
EQUINOX13 小时前
思维+贪心,CF 1210B - Marcin and Training Camp
算法·数学建模·动态规划
hn小菜鸡3 小时前
LeetCode 面试经典150题 69.x的平方根
算法·leetcode·面试
_GR4 小时前
每日OJ题_牛客_JOR26最长回文子串_C++_Java
java·数据结构·c++·算法·动态规划