Leetcode 218 Solution

This article provides solution to leetcode question 218 (the-skyline-problem)

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

Solution

class Solution {
public:
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        vector<pair<int, int>> a;

        for (auto building : buildings)
        {
            if (building[2] == 0)
                continue;

            a.push_back(make_pair(building[0], -building[2]));
            a.push_back(make_pair(building[1], building[2]));
        }

        sort(a.begin(), a.end());

        int last_top = 0;
        multiset<int, greater<int>> s;
        s.insert(0);
        vector<pair<int, int>> res;
        for (auto pair : a)
        {
            if (pair.second < 0)
                s.insert(-pair.second);
            else
                s.erase(s.find(pair.second));

            if (last_top != *s.begin())
            {
                res.push_back(make_pair(pair.first, *s.begin()));
                last_top = *s.begin();
            }
        }

        return res;
    }
};