Java for LeetCode 218 The Skyline Problem【HARD】

本文介绍了一种简化方法,通过横坐标排序和遍历求拐点,输出城市建筑群形成的天际线。利用优先队列保存当前楼顶高度,遇到左右节点时更新高度信息,并检测拐点输出结果。

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

解题思路:

本题如果一个矩形一个矩形的加入,涉及到回溯问题,比较复杂。

一个简便的思路是,根据横坐标排序,然后遍历求拐点。求拐点的时候用一个最大化heap来保存当前的楼顶高度,遇到左边节点,就在heap中插入高度信息,遇到右边节点就 从heap中删除高度。分别用pre与cur来表示之前的高度与当前的高度,当cur != pre的时候说明出现了拐点。JAVA实现如下:

	static public List<int[]> getSkyline(int[][] buildings) {
		List<int[]> res = new ArrayList<int[]>();
		PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,
				new Comparator<Integer>() {
					public int compare(Integer a, Integer b) {
						return b - a;
					}
				});
		List<int[]> bl = new ArrayList<int[]>();
		for (int i = 0; i < buildings.length; i++) {
			bl.add(new int[] { buildings[i][0], buildings[i][2] });
			bl.add(new int[] { buildings[i][1], -buildings[i][2] });
		}
		Collections.sort(bl, new Comparator<int[]>() {
			public int compare(int[] a, int[] b) {
				return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0];
			}
		});
		int pre = 0, cur = 0;
		for (int i = 0; i < bl.size(); i++) {
			int[] b = bl.get(i);
			if (b[1] > 0) {
				maxHeap.add(b[1]);
				cur = maxHeap.peek();
			} else {
				maxHeap.remove(-b[1]);
				cur = (maxHeap.peek() == null) ? 0 : maxHeap.peek();
			}
			if (cur != pre) {
				res.add(new int[] { b[0], cur });
				pre = cur;
			}
		}
		return res;
	}

 

转载于:https://www.cnblogs.com/tonyluis/p/4564617.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值