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;
    }
};
相关推荐
YY_TJJ22 分钟前
算法题——贪心算法
算法·贪心算法
C++ 老炮儿的技术栈28 分钟前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio
RainbowC01 小时前
GapBuffer高效标记管理算法
android·算法
liu****1 小时前
10.queue的模拟实现
开发语言·数据结构·c++·算法
mit6.8241 小时前
10.17 枚举中间|图论
算法
让我们一起加油好吗2 小时前
【基础算法】01BFS
数据结构·c++·算法·bfs·01bfs
孤狼灬笑2 小时前
机器学习十大经典算法解析与对比
人工智能·算法·机器学习
1白天的黑夜13 小时前
递归-24.两两交换链表中的节点-力扣(LeetCode)
数据结构·c++·leetcode·链表·递归
1白天的黑夜13 小时前
递归-206.反转链表-力扣(LeetCode)
数据结构·c++·leetcode·链表·递归
靠近彗星3 小时前
3.1 栈
数据结构·算法