Skip to content

Commit 34ee3d3

Browse files
add a solution for 849
1 parent a8cfdb2 commit 34ee3d3

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

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

+31
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.fishercoder.solutions;
22

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

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

+4
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,23 @@
99
public class _849Test {
1010

1111
private static _849.Solution1 solution1;
12+
private static _849.Solution2 solution2;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _849.Solution1();
17+
solution2 = new _849.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
assertEquals(2, solution1.maxDistToClosest(new int[]{1, 0, 0, 0, 1, 0, 1}));
23+
assertEquals(2, solution2.maxDistToClosest(new int[]{1, 0, 0, 0, 1, 0, 1}));
2124
}
2225

2326
@Test
2427
public void test2() {
2528
assertEquals(3, solution1.maxDistToClosest(new int[]{1, 0, 0, 0}));
29+
assertEquals(3, solution2.maxDistToClosest(new int[]{1, 0, 0, 0}));
2630
}
2731
}

0 commit comments

Comments
 (0)