Skip to content

Commit b8f54ec

Browse files
HARD/src/hard/TheSkylineProblem.java
1 parent 81cff62 commit b8f54ec

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

HARD/src/hard/TheSkylineProblem.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package hard;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
import java.util.TreeMap;
7+
8+
public class TheSkylineProblem {
9+
10+
class BuildingPoint implements Comparable<BuildingPoint>{
11+
int x;
12+
boolean isStart;
13+
int h;
14+
15+
public BuildingPoint(int x, boolean isStart, int h){
16+
this.x = x;
17+
this.h = h;
18+
this.isStart = isStart;
19+
}
20+
21+
@Override
22+
public int compareTo(BuildingPoint o){
23+
if(this.x != o.x){
24+
return this.x - o.x;
25+
} else {
26+
if(this.isStart && o.isStart){
27+
return o.h - this.h;
28+
} else if(this.isStart && !o.isStart){
29+
return -this.h - o.h;
30+
} else if(!this.isStart && !o.isStart){
31+
return this.h - o.h;
32+
} else {
33+
return this.h + o.h;
34+
}
35+
}
36+
}
37+
}
38+
39+
public List<int[]> getSkyline(int[][] buildings) {
40+
BuildingPoint[] bps = new BuildingPoint[buildings.length*2];
41+
int index = 0;
42+
for(int[] building : buildings){
43+
BuildingPoint bp1 = new BuildingPoint(building[0], true, building[2]);
44+
BuildingPoint bp2 = new BuildingPoint(building[1], false, building[2]);
45+
bps[index++] = bp1;
46+
bps[index++] = bp2;
47+
}
48+
49+
//this is one key step:
50+
Arrays.sort(bps);
51+
52+
List<int[]> result = new ArrayList();
53+
TreeMap<Integer, Integer> treeMap = new TreeMap();
54+
treeMap.put(0, 1);
55+
int prevMaxH = 0;
56+
for(BuildingPoint bp : bps){
57+
//if it's a starting point, we'll add it into the final result
58+
if(bp.isStart){
59+
if(treeMap.containsKey(bp.h)) treeMap.put(bp.h, treeMap.get(bp.h)+1);
60+
else treeMap.put(bp.h, 1);
61+
}
62+
63+
//if it's an ending point, we'll decrement/remove this entry
64+
else if(!bp.isStart){
65+
if(treeMap.containsKey(bp.h) && treeMap.get(bp.h) > 1) treeMap.put(bp.h, treeMap.get(bp.h)-1);
66+
else treeMap.remove(bp.h);
67+
}
68+
69+
int currMaxH = treeMap.lastKey();
70+
if(currMaxH != prevMaxH){
71+
result.add(new int[]{bp.x, currMaxH});
72+
prevMaxH = currMaxH;
73+
}
74+
75+
}
76+
77+
return result;
78+
}
79+
80+
}

0 commit comments

Comments
 (0)