218. The Skyline Problem

本文介绍了一种解决城市天际线问题的高效算法。通过定义边类存储建筑的起始位置、高度等信息,并使用优先队列来跟踪当前可见的最大高度变化,最终输出天际线的关键点。
class Edge {
	int x;
	int height;
	boolean isStart;
 
	public Edge(int x, int height, boolean isStart) {
		this.x = x;
		this.height = height;
		this.isStart = isStart;
	}
}

public List<int[]> getSkyline(int[][] buildings) {
	List<int[]> result = new ArrayList<int[]>();
 
	if (buildings == null || buildings.length == 0
			|| buildings[0].length == 0) {
		return result;
	}
 
	List<Edge> edges = new ArrayList<Edge>();
 
	// add all left/right edges
	for (int[] building : buildings) {
		Edge startEdge = new Edge(building[0], building[2], true);
		edges.add(startEdge);
		Edge endEdge = new Edge(building[1], building[2], false);
		edges.add(endEdge);
	}
 
	// sort edges 
	Collections.sort(edges, new Comparator<Edge>() {
		public int compare(Edge a, Edge b) {
			if (a.x != b.x)
				return Integer.compare(a.x, b.x);
 
			if (a.isStart && b.isStart) {
				return Integer.compare(b.height, a.height);
			}
 
			if (!a.isStart && !b.isStart) {
				return Integer.compare(a.height, b.height);
			}
 
			return a.isStart ? -1 : 1;
		}
	});
 
	// process edges
	PriorityQueue<Integer> heightHeap = new PriorityQueue<Integer>(10, Collections.reverseOrder());
 
	for (Edge edge : edges) {
		if (edge.isStart) {
			if (heightHeap.isEmpty() || edge.height > heightHeap.peek()) {
				result.add(new int[] { edge.x, edge.height });
			}
			heightHeap.add(edge.height);
		} else {
			heightHeap.remove(edge.height);
 
			if(heightHeap.isEmpty()){
				result.add(new int[] {edge.x, 0});
			}else if(edge.height > heightHeap.peek()){
				result.add(new int[]{edge.x, heightHeap.peek()});
			}
		}
	}
 
	return result;
}

 

转载于:https://www.cnblogs.com/zmyvszk/p/5874449.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值