LeetCode刷题记154-218. 天际线问题【再做一遍】

4 篇文章 0 订阅

LeetCode刷题记154

218. 天际线问题

题目
在这里插入图片描述在这里插入图片描述在这里插入图片描述

class Solution {
    class MyComparator implements Comparator<int[]> {
        @Override
        public int compare(int[] a, int[] b) {
            if (a[0] != b[0]) {
                // 无论是建筑的左边还是右边线条,首先按x的位置排序,x小的在前面
                return a[0] - b[0]; 
            } else {
                // x位置一样的,按照高度排序
                // 建筑右边线条矮的在前面,左边线条高的在前面
                // 不同建筑的左右线条在同一个位置,则左边那条线在前面
                return a[1] - b[1]; 
            }
        }
    }
    public List<List<Integer>> getSkyline(int[][] buildings) { 
        List<List<Integer>> ans = new ArrayList<>();
        PriorityQueue<int[]> lines = new PriorityQueue<int[]>(new MyComparator());
        for (int i = 0; i < buildings.length; i ++) {
            lines.add(new int[]{buildings[i][0], -buildings[i][2]});
            lines.add(new int[]{buildings[i][1], buildings[i][2]});
        }
        // height存放当前可以涵盖到后面线条的建筑物的左边线条的高度,是大顶堆
        PriorityQueue<Integer> height = new PriorityQueue<Integer>((a, b) -> b - a);
        height.add(0); // 存放最开始的高度0
        int pre_h = 0; // 前一个高度
        while (!lines.isEmpty()) {
            int[] tmp = lines.poll(); 
            if (tmp[1] < 0) { // 是建筑的左边线条,高度直接入队列
                height.add(-tmp[1]);
            } else { // 右边线条出现了,那么之前存在的这个高度失效
                height.remove(tmp[1]);
            }
            if (height.peek() != pre_h) { // 当前有效的最高的高度与上一个不一样,说明有转折点
                ans.add(Arrays.asList(new Integer[]{tmp[0], height.peek()}));
                // ans.add(Arrays.asList(new int[]{tmp[0], height.peek()}));
                // 这里有一个神奇的知识点,注释里的写法,obj = Arrays.asList(new int[]{})
                // obj是List<int[]>类型的,而不是List<Integer>
                pre_h = height.peek();
            }
        }
        return ans;
    }
}

这个问题,我感觉好难呀,我没有想明白,所以还是看了题解才做出来的。
关于上面排序的详解:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值