File tree Expand file tree Collapse file tree 2 files changed +24
-0
lines changed
main/java/com/fishercoder/solutions/fourththousand
test/java/com/fishercoder/fourththousand Expand file tree Collapse file tree 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) {
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}
Original file line number Diff line number Diff line change 88
99public 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
You can’t perform that action at this time.
0 commit comments