LeetCode 218: The Skyline Problem

本文介绍了一种计算由多个矩形建筑物组成的天际线轮廓的高效算法。通过记录每个建筑物的高度变化并使用优先队列来跟踪当前最高的建筑物,该算法能够正确地生成天际线轮廓的关键转折点。

Note:

1. There is a trick here: As it only gets the starting point, we can check each bound of the building. Also we have to have a "sign" to know when the bound is start when the bound is end.

2. REMEMBER to add 0 to the queue to avoid NPE. Also 0 represents there is no building there.

class Solution {
    public List<int[]> getSkyline(int[][] buildings) {
        if (buildings.length == 0) {
            return new ArrayList<>();
        }
        
        List<int[]> result = new ArrayList<>();
        List<int[]> height = new ArrayList<>();
        for (int[] building : buildings) {
            height.add(new int[]{building[0], -building[2]});
            height.add(new int[]{building[1], building[2]});
        }
        
        Collections.sort(height, (b1, b2) -> {return b1[0] == b2[0] ? b1[1] - b2[1] : b1[0] - b2[0];});
        PriorityQueue<Integer> queue = new PriorityQueue<>((i1, i2) -> (i2 - i1));
        queue.offer(0);
        int prev = 0;
        for (int[] vertical : height) {
            if (vertical[1] < 0) {
                queue.offer(-vertical[1]);
            } else {
                queue.remove(vertical[1]);
            }
            
            int current = queue.peek();
            if (prev != current) {
                result.add(new int[]{vertical[0], current});
                prev = current;
            }
        }
        return result;
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7473345.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值