File tree 2 files changed +24
-0
lines changed
main/java/com/fishercoder/solutions/fourththousand
test/java/com/fishercoder/fourththousand
2 files changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -16,4 +16,25 @@ public int numberOfChild(int n, int k) {
16
16
}
17
17
}
18
18
}
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
+ }
19
40
}
Original file line number Diff line number Diff line change 8
8
9
9
public class _3178Test {
10
10
private static _3178 .Solution1 solution1 ;
11
+ private static _3178 .Solution2 solution2 ;
11
12
12
13
@ BeforeEach
13
14
public void setup () {
14
15
solution1 = new _3178 .Solution1 ();
16
+ solution2 = new _3178 .Solution2 ();
15
17
}
16
18
17
19
@ Test
18
20
public void test1 () {
19
21
assertEquals (1 , solution1 .numberOfChild (3 , 5 ));
22
+ assertEquals (1 , solution2 .numberOfChild (3 , 5 ));
20
23
}
21
24
22
25
@ Test
You can’t perform that action at this time.
0 commit comments