Skip to content

Commit 1f58c68

Browse files
add a solution for 3178
1 parent d3e4dd9 commit 1f58c68

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

Diff for: src/main/java/com/fishercoder/solutions/fourththousand/_3178.java

+21
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,25 @@ public int numberOfChild(int n, int k) {
1616
}
1717
}
1818
}
19+
20+
public static class Solution2 {
21+
/**
22+
* Also, my completely original solution, much more elegant and efficient.
23+
*/
24+
public int numberOfChild(int n, int k) {
25+
//n - 1 is the number of steps is takes to finish from one end to the other
26+
// 2 * (n - 1) is the whole round trip, so after this, it's back to the starting point
27+
//so we only need to handle the modulo remainder of 2 * (n - 1)
28+
k = k % ((n - 1) * 2);
29+
if (k < n) {
30+
//in this case, we can directly return k
31+
return k;
32+
} else {
33+
//in this case, it's in the reverse direction, we deduct the number of steps needed to finish the forward direction first
34+
k -= n - 1;
35+
//then return the correct child index
36+
return n - k - 1;
37+
}
38+
}
39+
}
1940
}

Diff for: src/test/java/com/fishercoder/fourththousand/_3178Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88

99
public class _3178Test {
1010
private static _3178.Solution1 solution1;
11+
private static _3178.Solution2 solution2;
1112

1213
@BeforeEach
1314
public void setup() {
1415
solution1 = new _3178.Solution1();
16+
solution2 = new _3178.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals(1, solution1.numberOfChild(3, 5));
22+
assertEquals(1, solution2.numberOfChild(3, 5));
2023
}
2124

2225
@Test

0 commit comments

Comments
 (0)