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;
    }
};
相关推荐
流星白龙1 小时前
【C++算法】50.分治_归并_翻转对
c++·算法
Java致死2 小时前
费马小定理
算法·费马小定理
不吃元西3 小时前
leetcode 74. 搜索二维矩阵
算法·leetcode·矩阵
小开不是小可爱3 小时前
leetcode_454. 四数相加 II_java
java·数据结构·算法·leetcode
aaaweiaaaaaa4 小时前
蓝桥杯c ++笔记(含算法 贪心+动态规划+dp+进制转化+便利等)
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
Hesse4 小时前
希尔排序:Python语言实现
python·算法
h^hh4 小时前
pipe匿名管道实操(Linux)
数据结构·c++·算法
dr李四维4 小时前
解决缓存穿透的布隆过滤器与布谷鸟过滤器:谁更适合你的应用场景?
redis·算法·缓存·哈希算法·缓存穿透·布隆过滤器·布谷鸟过滤器
亓才孓4 小时前
[leetcode]01背包问题
算法·leetcode·职场和发展
学习编程的gas5 小时前
数据结构——二叉树
数据结构·算法