-
Notifications
You must be signed in to change notification settings - Fork 0
/
S46.java
43 lines (39 loc) · 1.06 KB
/
S46.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package S41_50;
import java.util.ArrayList;
import java.util.List;
/**
* 圆圈中最后剩下的数
* Created by Elvis on 2019/12/30.
*/
public class S46 {
public static void main(String[] args) {
System.out.println(LastRemaining_Solution(7, 3));
}
public static int LastRemaining_Solution(int n, int m) {
if (n < 1 || m < 1) return -1;
int ans = 0;
for (int i = 2; i <= n; i++) {
ans = (ans + m) % i;
}
return ans;
}
public static int LastRemaining_Solution1(int n, int m) {
if (n < 1 || m < 1) return -1;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(i);
}
int cur = -1;
while (list.size() > 1) {
for (int i = 0; i < m; i++) {
cur++;
if (cur == list.size()) {
cur = 0;
}
}
list.remove(cur);
cur--;
}
return list.get(0);
}
}