Skip to content

Commit 25e0c84

Browse files
committed
剑指Offer,孩子们的游戏
1 parent fb64162 commit 25e0c84

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

swordoffer/LastRemaining.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* ½£Ö¸Offer£¬º¢×ÓÃǵÄÓÎÏ·
3+
*/
4+
import java.util.*;
5+
6+
public class LastRemaining {
7+
8+
public static void main(String[] args) {
9+
System.out.println(LastRemaining_Solution(5, 3));
10+
}
11+
12+
public static int LastRemaining_Solution(int n, int m) {
13+
14+
if (n == 0 || m == 0) {
15+
return -1;
16+
}
17+
List<Integer> list = new ArrayList<>();
18+
19+
for (int i = 0; i < n; i++) {
20+
list.add(i);
21+
}
22+
23+
int cur = 0;
24+
while (list.size() > 1) {
25+
26+
for (int i = 0; i < m; i++) {
27+
if (i == 0) {
28+
cur--;
29+
}
30+
cur++;
31+
if (cur == list.size()) {
32+
cur = 0;
33+
}
34+
}
35+
list.remove(cur);
36+
37+
}
38+
return list.get(0);
39+
}
40+
}

0 commit comments

Comments
 (0)