-
Notifications
You must be signed in to change notification settings - Fork 0
/
218-SkylineProblem.java
65 lines (55 loc) · 2.12 KB
/
218-SkylineProblem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class BuildingPoint implements Comparable<BuildingPoint>{
int x;
int height;
boolean isStart;
public int compareTo(BuildingPoint o){
if(this.x!=o.x)
return this.x - o.x;
else
return (this.isStart? -this.height:this.height) - (o.isStart? -o.height:o.height);
}
}
class Solution {
public List<int[]> getSkyline(int[][] buildings) {
BuildingPoint[] BuildingPoints = new BuildingPoint[buildings.length*2];
int index = 0;
for(int[] building:buildings){
BuildingPoints[index] = new BuildingPoint();
BuildingPoints[index].x = building[0];
BuildingPoints[index].isStart = true;
BuildingPoints[index].height = building[2];
BuildingPoints[index+1] = new BuildingPoint();
BuildingPoints[index+1].x = building[1];
BuildingPoints[index+1].isStart = false;
BuildingPoints[index+1].height = building[2];
index = index+2;
}
Arrays.sort(BuildingPoints);
TreeMap<Integer,Integer> queue = new TreeMap<>();
queue.put(0,1);
int prevMaxHeight = 0;
List<int[]> result = new ArrayList<>();
for(BuildingPoint buildingpoint:BuildingPoints){
if(buildingpoint.isStart){
queue.compute(buildingpoint.height, (key,value)->{
if(value!=null)
return value+1;
return 1;
});
}
else{
queue.compute(buildingpoint.height, (key,value)->{
if(value==1)
return null;
return value-1;
});
}
int maxheight = queue.lastKey();
if(maxheight!=prevMaxHeight){
result.add(new int[]{buildingpoint.x,maxheight});
prevMaxHeight = maxheight;
}
}
return result;
}
}