The Skyline Problem

本文介绍了一种高效计算城市建筑天际线轮廓的算法。通过遍历所有建筑物的起点和终点,结合优先队列记录当前可见的最大高度,从而得到最终的天际线轮廓。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Solution {
    public List<int[]> getSkyline(int[][] buildings) {
        List<int[]> res = new LinkedList<>();
        List<int[]> heights = new LinkedList<>();
        for (int[] b: buildings) {
            heights.add(new int[]{b[0], -b[2]});
            heights.add(new int[]{b[1], b[2]});
        }
        Collections.sort(heights, new Comparator<int[]>(){
            @Override
            public int compare(int[] a, int[] b) {
                if (a[0] != b[0]) {
                    return a[0] - b[0];
                } else {
                    return a[1] - b[1];
                }
            }
        });
        PriorityQueue<Integer> queue = new PriorityQueue<>(11, new Comparator<Integer>(){
            @Override
            public int compare(Integer a, Integer b){
                return b - a;
            }
        });
        int prev = 0;
        queue.offer(0);
        for (int[] b: heights) {
            if (b[1] < 0) {
                queue.offer(-b[1]);
            } else {
                queue.remove(b[1]);
            }
            int cur = queue.peek();
            if (prev != cur) {
                res.add(new int[]{b[0], cur});
                prev = cur;
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值