ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

力扣218.天际线问题

2022-01-19 13:33:52  阅读:130  来源: 互联网

标签:10 12 15 天际线 get int queue 218 力扣


用line sweep

输入(x1,x2,y),左上角顶点用(x1,-y)表示,右上角顶点用(x2,y)表示

如示例,输入:

[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]

及每个转折点为:

[2,10],[9,10],[3,15],[7,15],[5,12],[12,12],[15,10],[20,10],[19,8],[24,8]

按上述方法表示后并排序,变为:

[2,-10],[3,-15],[5,-12],[7,15],[9,10],[12,12],[15,-10],[19,-8],[20,10],[24,8]

从左至右扫描每一条边缘线,左边缘线计入高度,右边缘线清除高度

如果内部高度发生了变化,说明到了关键点

class Solution {
    public List<List<Integer>> getSkyline(int[][] buildings) {
        List<List<Integer>> points = new ArrayList<>();
        //左上角和右上角坐标
        for(int[] b :buildings){
            points.add(Arrays.asList(b[0],-b[2]));
            points.add(Arrays.asList(b[1],b[2]));
        }
        //所有坐标排序
        points.sort(
            (a, b) -> {
                int x1 = a.get(0),y1 = a.get(1);
                int x2 = b.get(0),y2 = b.get(1);
                if(x1 != x2)
                    return x1 - x2;
                else
                    return y1 - y2;
            }
        );
        Queue<Integer> queue = new PriorityQueue<>((a,b) -> b - a);
        queue.offer(0);
        int preMax = 0;
        List<List<Integer>> res = new ArrayList<>();
        for(List<Integer> p : points){
            int x = p.get(0),y = p.get(1);
            //左上角坐标
            if(y < 0)
                queue.offer(-y);
            //右上角坐标
            else
                queue.remove(y);
            int curMax = queue.peek();
            //最大值更新了,加入当前结果
            if(curMax != preMax){
                res.add(Arrays.asList(x,curMax));
                preMax = curMax;
            }
        }
        return res;
    }
}

标签:10,12,15,天际线,get,int,queue,218,力扣
来源: https://blog.csdn.net/lamycies/article/details/122568622

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有