C++ | Leetcode C++题解之第218题天际线问题

题目:

C++ | Leetcode C++题解之第218题天际线问题_第1张图片

题解:

class Solution {
public:
    vector> getSkyline(vector>& buildings) {
        auto cmp = [](const pair& a, const pair& b) -> bool { return a.second < b.second; };
        priority_queue, vector>, decltype(cmp)> que(cmp);

        vector boundaries;
        for (auto& building : buildings) {
            boundaries.emplace_back(building[0]);
            boundaries.emplace_back(building[1]);
        }
        sort(boundaries.begin(), boundaries.end());

        vector> ret;
        int n = buildings.size(), idx = 0;
        for (auto& boundary : boundaries) {
            while (idx < n && buildings[idx][0] <= boundary) {
                que.emplace(buildings[idx][1], buildings[idx][2]);
                idx++;
            }
            while (!que.empty() && que.top().first <= boundary) {
                que.pop();
            }

            int maxn = que.empty() ? 0 : que.top().second;
            if (ret.size() == 0 || maxn != ret.back()[1]) {
                ret.push_back({boundary, maxn});
            }
        }
        return ret;
    }
};

你可能感兴趣的:(经验分享,C++,Leetcode,题解)