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

Commit34ee3d3

Browse files
add a solution for 849
1 parenta8cfdb2 commit34ee3d3

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_849.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
packagecom.fishercoder.solutions;
22

3+
importjava.util.TreeSet;
4+
35
publicclass_849 {
46
publicstaticclassSolution1 {
57
intmaxDist =0;
@@ -45,4 +47,33 @@ private void extend(int[] seats, int position) {
4547
maxDist =Math.max(maxDist,maxReach);
4648
}
4749
}
50+
51+
publicstaticclassSolution2 {
52+
/**
53+
* my completely original solution on 9/13/2021.
54+
*/
55+
publicintmaxDistToClosest(int[]seats) {
56+
intmaxDistance =0;
57+
TreeSet<Integer>treeMap =newTreeSet<>();
58+
for (inti =0;i <seats.length;i++) {
59+
if (seats[i] ==1) {
60+
treeMap.add(i);
61+
}
62+
}
63+
for (inti =0;i <seats.length;i++) {
64+
if (seats[i] ==0) {
65+
IntegerleftNeighbor =treeMap.floor(i);
66+
IntegerrightNeighbor =treeMap.ceiling(i);
67+
if (leftNeighbor !=null &&rightNeighbor !=null) {
68+
maxDistance =Math.max(maxDistance,Math.min(i -leftNeighbor,rightNeighbor -i));
69+
}elseif (leftNeighbor ==null) {
70+
maxDistance =Math.max(maxDistance,rightNeighbor -i);
71+
}else {
72+
maxDistance =Math.max(maxDistance,i -leftNeighbor);
73+
}
74+
}
75+
}
76+
returnmaxDistance;
77+
}
78+
}
4879
}

‎src/test/java/com/fishercoder/_849Test.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,23 @@
99
publicclass_849Test {
1010

1111
privatestatic_849.Solution1solution1;
12+
privatestatic_849.Solution2solution2;
1213

1314
@BeforeClass
1415
publicstaticvoidsetup() {
1516
solution1 =new_849.Solution1();
17+
solution2 =new_849.Solution2();
1618
}
1719

1820
@Test
1921
publicvoidtest1() {
2022
assertEquals(2,solution1.maxDistToClosest(newint[]{1,0,0,0,1,0,1}));
23+
assertEquals(2,solution2.maxDistToClosest(newint[]{1,0,0,0,1,0,1}));
2124
}
2225

2326
@Test
2427
publicvoidtest2() {
2528
assertEquals(3,solution1.maxDistToClosest(newint[]{1,0,0,0}));
29+
assertEquals(3,solution2.maxDistToClosest(newint[]{1,0,0,0}));
2630
}
2731
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp