![]()
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
List<List<Integer>> res = new ArrayList<>();
Node[] nodes = new Node[buildings.length * 2];
int k = 0;
for(int[] build : buildings) {
nodes[k * 2] = new Node(true,build[0],build[2]);
nodes[k++ * 2 + 1] = new Node(false,build[1],build[2]);
}
Arrays.sort(nodes,new Comparator1());
TreeMap<Integer,Integer> hMap = new TreeMap<>();
TreeMap<Integer,Integer> pMap = new TreeMap<>();
for(Node node : nodes) {
if(node.isUp) { // 上升阶段加入高度
hMap.put(node.h,hMap.getOrDefault(node.h,0)+1);
} else { // 下降阶段去掉高度
if(hMap.get(node.h) == 1) {
hMap.remove(node.h);
} else {
hMap.put(node.h,hMap.get(node.h)-1);
}
}
// 每次更新当前位置的最大高度
if(hMap.isEmpty()) {
pMap.put(node.pos,0); // 表示当前最高高度为0,因为记录高度的hMap为空
} else {
pMap.put(node.pos,hMap.lastKey());
}
}
int preHigh = 0;
for(int pos : pMap.keySet()) {
int high = pMap.get(pos);
if(preHigh != high) { // 高度变化的时候加入高度的起点
res.add(Arrays.asList(pos,high));
}
preHigh = high;
}
return res;
}
}
class Comparator1 implements Comparator<Node> {
public int compare(Node n1, Node n2) {
if(n1.pos != n2.pos) {
return n1.pos - n2.pos;
}
if(n1.isUp) return 1; // 上升排到后面,下降排到前面 因为相同位置要的是上升点的位置,所以上升点排到后面!
else return -1;
}
}
class Node {
boolean isUp;
int pos, h;
public Node(boolean isUp, int pos, int h) {
this.isUp = isUp;
this.pos = pos;
this.h = h;
}
}