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;
    }
};
相关推荐
Dream it possible!16 分钟前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉17 分钟前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生18 分钟前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴22 分钟前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing22 分钟前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财23 分钟前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程23 分钟前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财24 分钟前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
瓦力的狗腿子27 分钟前
Starlink卫星动力学系统仿真建模番外篇6-地球敏感器
算法·数学建模·simulink
一只码代码的章鱼1 小时前
数据结构与算法-搜索-剪枝
算法·深度优先·剪枝