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;
    }
};
相关推荐
j_xxx404_15 分钟前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
南莺莺20 分钟前
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判别,表达式中的括号是否配对,以字符“\0“作为算术表达式的结束符
c语言·数据结构·算法·
Lris-KK27 分钟前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
THMAIL36 分钟前
深度学习从入门到精通 - 神经网络核心原理:从生物神经元到数学模型蜕变
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
珍珠是蚌的眼泪39 分钟前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦41 分钟前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode
墨染点香44 分钟前
LeetCode 刷题【61. 旋转链表】
算法·leetcode·职场和发展
岁忧1 小时前
(LeetCode 面试经典 150 题) 200. 岛屿数量(深度优先搜索dfs || 广度优先搜索bfs)
java·c++·leetcode·面试·go·深度优先
一枝小雨1 小时前
【OJ】C++ vector类OJ题
数据结构·c++·算法·leetcode·oj题
Tisfy1 小时前
LeetCode 3516.找到最近的人:计算绝对值大小
数学·算法·leetcode·题解