分析一下:
public static class Node{
public boolean isUp;//记录是向上还是向下
public int posi;//记录位置
public int h;//记录高度
public Node(boolean bORe,int position,int height)
//布尔值true为上,false为下
{
isUp=bORe;
posi=position;
h=height;
}
}
public static class NodeComparator implements Comparator<Node>{
public int compare(Node o1,Node o2) {
if(o1.posi!=o2.posi){
//位置不同,位置小的在前面
return o1.posi-o2.posi;
}
if(o1.isUp!=o2.isUp)
//位置相同,升的位置在前面
{
return o1.isUp ? -1:1;
}
return 0;
}
}
public static List<List<Integer>> buildingOutlilne(int[][] buildings)
{
Node[] nodes=new Node[buildings.length*2];
for(int i=0;i<buildings.length;i++)
{
nodes[i*2]=new Node(true,buildings[i][0],buildings[i][2]);
//上,开始位置,高度
nodes[i*2+1]=new Node(false,buildings[i][0],buildings[i][2]);
//下,结束位置,高度
}
Arrays.sort(nodes, new NodeComparator());
TreeMap<Integer,Integer> htMap=new TreeMap<>();
//高度,次数
TreeMap<Integer,Integer> pmMap=new TreeMap<>();
for(int i=0;i<nodes.length;i++)
{
if(nodes[i].isUp)
//如果上升
{
if(!htMap.containsKey(nodes[i].h)) {
//不含有就是第一次出现
htMap.put(nodes[i].h, 1);
}else {
//不是第一次就在以前次数上+1
htMap.put(nodes[i].h,htMap.get(nodes[i].h)+1);
}
}
//如果下降
else {
if(htMap.containsKey(nodes[i].h))
//如果出现过
{
//出现过1次
if(htMap.get(nodes[i].h)==1) {
htMap.remove(nodes[i].h);
}
//出现过多次
else {
htMap.put(nodes[i].h, htMap.get(nodes[i].h)-1);
}
}
}
//每个点的达到的最大高度:位置+高度
if(htMap.isEmpty()) {
pmMap.put(nodes[i].posi, 0);
}else {
pmMap.put(nodes[i].posi, htMap.lastKey());
//htMap的key是高度
}
}
List<List<Integer>> res=new ArrayList<>();
int start=0;
int height=0;//之前的高度
for (Entry<Integer,Integer>entry:pmMap.entrySet())
//Entry是map下的方法,用来遍历map
{
int curPosition=entry.getKey();//当前位置
int curMaxHeight=entry.getValue();//当前高度
if(height!=curMaxHeight)//现在的高度!=以前的高度
{
if(height!=0) {//高度!=0
List<Integer>newRecord=new ArrayList<Integer>();
newRecord.add(start);//起始位置
newRecord.add(curPosition);//结束位置
newRecord.add(height);//高度
res.add(newRecord);
}
start=curPosition;
height=curMaxHeight;
}
}
return res;
}