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;
    }
};
相关推荐
FPGA_无线通信13 小时前
OFDM 精频偏补偿
算法·fpga开发
FMRbpm13 小时前
栈练习--------从链表中移除节点(LeetCode 2487)
数据结构·c++·leetcode·链表·新手入门
程序员-King.13 小时前
day109—同向双指针(字符串)—每个字符最多出现两次的最长子字符串(LeetCode-3090)
算法·leetcode·双指针
青山的青衫13 小时前
【单调栈和单调队列】LeetCode hot100+面试高频
算法·leetcode·面试
俊俊谢14 小时前
【浮点运算性能优化】浮点转定点算法库的多平台通用移植方案与性能评估优化
算法·性能优化·c·浮点转定点·多平台移植
电饭叔14 小时前
Luhn算法与信用卡识别完善《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之三
android·python·算法
bbq粉刷匠14 小时前
力扣-电话号码组合
java·算法
狗头实习生14 小时前
电话号码字母组合
java·算法·leetcode
C雨后彩虹14 小时前
矩阵扩散问题
java·数据结构·算法·华为·面试
独自破碎E14 小时前
力场重叠问题
java·开发语言·算法