1. 程式人生 > >Leetcode 218. The Skyline Problem

Leetcode 218. The Skyline Problem

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()