218. The Skyline Problem
题意
一座城市的天际线是从远处看时,该城市所有建筑物形成的轮廓的外部轮廓。给定所有建筑的位置和高度,返回这些建筑共同形成的天际线。
每个建筑物的几何信息在阵列建筑物中给出
其中建筑物[i]=[lefti,righti,heighti]:
lefti是第i个建筑左边缘的x坐标。
righti是第i个建筑右边缘的x坐标。
heighti是第i栋楼的高度。
你可以假设所有的建筑都是完美的长方形,坐落在高度为0的绝对平坦的表面上。
天际线应表示为按x坐标排序的“关键点”列表,形式为[[x1,y1],[x2,y2],…]。
每个关键点都是天际线中某个水平线段的左端点,但列表中的最后一点除外,该点始终具有y坐标0,用于标记天际线的终点,即最右边的建筑的终点。最左边和最右边建筑之间的任何地面都应该是天际线轮廓的一部分。
注意:输出天际线中不能有高度相等的连续水平线。例如,[…,[2 3],[4 5],[7 5],[11 5],[12 7],…]是不可接受的;高度5的三行应在最终输出中合并为一行,例如:[…,[2 3],[4 5],[12 7],…]
Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Explanation:
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in f
igure B represent the key points in the output list.
思路
代码
Java实现
import java.util.*;
class Solution
{
public List<List<Integer>> getSkyline(int[][] buildings)
{
List<List<Integer>> answer = new ArrayList<>();
List<int[]> buildLines = new ArrayList<>();//天际线
for (int[] points : buildings)
{
//拆分
// build[0, 1, 2]
// build[left, right, height]
buildLines.add(new int[] { points[0], -points[2] });
buildLines.add(new int[] { points[1], points[2] });
}
// 从左往右再从小到大排序
// buildLines[0, 1]
// buildLines[bound, height]
buildLines.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
//创建最大堆
var maxHeap = new PriorityQueue<Integer>((a, b) -> b - a);
maxHeap.add(0);
int Highest = 0;//当前堆中最大高度
//遍历buildlines数组
for (int[] points : buildLines)
{
if (points[1] < 0)
{
maxHeap.add(-points[1]);
}
else
{
maxHeap.remove(points[1]);
}
//当前最大高度
int nowHeight=0;
nowHeight = maxHeap.peek();
//加入轮廓点
if (nowHeight != Highest)
{
answer.add(Arrays.asList(points[0], nowHeight));
Highest = nowHeight;
}
}
return answer;
}
}