Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb8f54ec

Browse files
HARD/src/hard/TheSkylineProblem.java
1 parent81cff62 commitb8f54ec

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+
packagehard;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.Arrays;
5+
importjava.util.List;
6+
importjava.util.TreeMap;
7+
8+
publicclassTheSkylineProblem {
9+
10+
classBuildingPointimplementsComparable<BuildingPoint>{
11+
intx;
12+
booleanisStart;
13+
inth;
14+
15+
publicBuildingPoint(intx,booleanisStart,inth){
16+
this.x =x;
17+
this.h =h;
18+
this.isStart =isStart;
19+
}
20+
21+
@Override
22+
publicintcompareTo(BuildingPointo){
23+
if(this.x !=o.x){
24+
returnthis.x -o.x;
25+
}else {
26+
if(this.isStart &&o.isStart){
27+
returno.h -this.h;
28+
}elseif(this.isStart && !o.isStart){
29+
return -this.h -o.h;
30+
}elseif(!this.isStart && !o.isStart){
31+
returnthis.h -o.h;
32+
}else {
33+
returnthis.h +o.h;
34+
}
35+
}
36+
}
37+
}
38+
39+
publicList<int[]>getSkyline(int[][]buildings) {
40+
BuildingPoint[]bps =newBuildingPoint[buildings.length*2];
41+
intindex =0;
42+
for(int[]building :buildings){
43+
BuildingPointbp1 =newBuildingPoint(building[0],true,building[2]);
44+
BuildingPointbp2 =newBuildingPoint(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 =newArrayList();
53+
TreeMap<Integer,Integer>treeMap =newTreeMap();
54+
treeMap.put(0,1);
55+
intprevMaxH =0;
56+
for(BuildingPointbp :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+
elsetreeMap.put(bp.h,1);
61+
}
62+
63+
//if it's an ending point, we'll decrement/remove this entry
64+
elseif(!bp.isStart){
65+
if(treeMap.containsKey(bp.h) &&treeMap.get(bp.h) >1)treeMap.put(bp.h,treeMap.get(bp.h)-1);
66+
elsetreeMap.remove(bp.h);
67+
}
68+
69+
intcurrMaxH =treeMap.lastKey();
70+
if(currMaxH !=prevMaxH){
71+
result.add(newint[]{bp.x,currMaxH});
72+
prevMaxH =currMaxH;
73+
}
74+
75+
}
76+
77+
returnresult;
78+
}
79+
80+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp