其他分享
首页 > 其他分享> > 力扣 218. 天际线问题 堆 扫描线

力扣 218. 天际线问题 堆 扫描线

作者:互联网

https://leetcode-cn.com/problems/the-skyline-problem/
在这里插入图片描述
思路:首先意识到每个建筑物的左右端点都有可能成为我们所关注的轮廓点,按照天际线的输出方式,我们应该读入这些端点并按照从小到大的顺序排序。然后考虑在每一个端点 p x p_x px​的输出,实际上就是计算直线 x = p x x=p_x x=px​与建筑物相交点的 y y y坐标的最大值,如果没有输出0即可。交点y坐标不就是建筑物的高度嘛, O ( n ) O(n) O(n)遍历求最大高度肯定是不可取的(会超时),用堆维护即可。

struct Node{
    int r,h;
    Node(int r,int h):r(r),h(h){}
    bool operator <(const Node& a)const
    {
        return h<a.h;
    }
};

class Solution {
public:
    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
        vector<int> pos;
        for(vector<int>& build:buildings)
            pos.push_back(build[0]),pos.push_back(build[1]);
        sort(pos.begin(),pos.end());
        priority_queue<Node> q;
        int n=buildings.size(),idx=0;
        vector<vector<int>> ans;
        for(int p:pos)
        {
            while(idx<n&&buildings[idx][0]<=p)
            {
                q.emplace(buildings[idx][1],buildings[idx][2]);
                ++idx;
            }
            while(!q.empty()&&q.top().r<=p)
                q.pop();
            int ansh=0;
            if(!q.empty())
                ansh=q.top().h;
            if(ans.size()&&ansh==ans.back()[1])
                continue;
            ans.push_back({p,ansh});
        }
        return ans;
    }
};

标签:buildings,idx,天际线,int,pos,力扣,vector,build,扫描线
来源: https://blog.csdn.net/xiji333/article/details/118854725