[LeetCode]218. The Skyline Problem

https://leetcode.com/problems/the-skyline-problem/?tab=Description

由图片一转成图片二,输入是每个建筑左右边坐标以及高度[L, R, H]










将每个建筑左上和右上两个顶点抽出来排序,高度为负的是左顶点为正的是右顶点,然后过一遍treemap,遇到左顶点加入,遇到右顶点移除,如果当前高度与前一高度不同,那么当前顶点及treemap的当前最大高度即为所求一点

public class Solution {
    public List<int[]> getSkyline(int[][] buildings) {
        List<int[]> res = new LinkedList();
        List<int[]> height = new LinkedList();
        for (int[] building : buildings) {
            height.add(new int[]{building[0], -building[2]});
            height.add(new int[]{building[1], building[2]});
        }
        Collections.sort(height, new Comparator<int[]>() {
            public int compare(int[] i1, int[] i2) {
                if (i1[0] == i2[0]) {
                    return i1[1] - i2[1];
                } else {
                    return i1[0] - i2[0];
                }
            }
        });
        int prev = 0;
        TreeMap<Integer, Integer> map = new TreeMap(new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return i2 - i1;
            }    
        });
        map.put(0, 1);
        for (int[] h : height) {
            if (h[1] < 0) {
                map.put(-h[1], map.getOrDefault(-h[1], 0) + 1);
            } else {
                Integer cnt = map.get(h[1]);
                if (cnt == 1) {
                    map.remove(h[1]);
                } else {
                    map.put(h[1], map.get(h[1]) - 1);
                }
            }
            int cur = map.firstKey();
            if (cur != prev) {
                res.add(new int[]{h[0], cur});
                prev = cur;
            }
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值