Leetcode 218. The Skyline Problem

https://leetcode.com/problems/the-skyline-problem/description/

class Solution {
public:
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        vector<pair<int,int>>res;
        //use a pair-heights to save the {l, -h} {r, h} and then loop through heights
        //-h means left boundary, h means the right boundary
        vector<pair<int,int>>heights;
        //use multiset-m to save the heights, the multiset is sorted from small to big
        multiset<int>m;
        for(auto build : buildings)
        {
            heights.push_back({build[0], -build[2]});
            heights.push_back({build[1], build[2]});
        }
        
        sort(heights.begin(), heights.end());
        //insert 0 so that the first key point can be found 
        m.insert(0);
        int pre = 0;
        int cur = 0;
        
        for(auto height : heights)
        {
            //build the multiset
            //if it's -h, insert the left bounary in multiset
            if(height.second < 0)
            {
                m.insert(-height.second);        
            } //else if h, right boundary reached, remove it. And the bar ends.
            else
            {
                m.erase(m.find(height.second));
            }
            //find the biggest h
            cur = *m.rbegin();
            //save the key point
            if(cur != pre)
            {
                res.push_back({height.first, cur});
                pre = cur;
            }
        }
        
        return res;          
        
    }
};

不常用的data structure:
pair<int, int>
http://www.cplusplus.com/reference/utility/pair/
multiset内的数据是按BST排好序的.
http://www.cplusplus.com/reference/set/multiset/
std::multiset::rbegin
Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning).
Therefore, the val needs to get from *m.rbegin()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值