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

Commit1f58c68

Browse files
add a solution for 3178
1 parentd3e4dd9 commit1f58c68

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

‎src/main/java/com/fishercoder/solutions/fourththousand/_3178.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,25 @@ public int numberOfChild(int n, int k) {
1616
}
1717
}
1818
}
19+
20+
publicstaticclassSolution2 {
21+
/**
22+
* Also, my completely original solution, much more elegant and efficient.
23+
*/
24+
publicintnumberOfChild(intn,intk) {
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+
returnk;
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+
returnn -k -1;
37+
}
38+
}
39+
}
1940
}

‎src/test/java/com/fishercoder/fourththousand/_3178Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88

99
publicclass_3178Test {
1010
privatestatic_3178.Solution1solution1;
11+
privatestatic_3178.Solution2solution2;
1112

1213
@BeforeEach
1314
publicvoidsetup() {
1415
solution1 =new_3178.Solution1();
16+
solution2 =new_3178.Solution2();
1517
}
1618

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

2225
@Test

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp