1.题目
2.解法(for循环)
public class Solution {
public int LastRemaining_Solution(int n, int m) {
// 没有小朋友
if(n < 1 || m < 1){
return -1;
}
int count = 0;
// 记录出圈的小朋友
boolean[] arr = new boolean[n];
int len = n;
int i = 0;
end:
while(true) {
for (i = 0; i < n; i++) {
// 如果这个小朋友没有出圈,那么就可以报数
if(!arr[i]) {
++count;
// 还剩最后一个小朋友
if(len == 1 && count == 1){
break end;
}
// 报到第m个数时,小朋友出圈
if (count == m) {
arr[i] = true;
--len;
count = 0;
}
}
}
}
return i;
}
}
每删除一个数,都要遍历m个数,总共n个数,时间复杂度为O(nm),空间复杂度为O(n)
3.高级解法(数学公式法)
public class Solution {
public int LastRemaining_Solution(int n, int m) {
// 不满足的条件
if (n <= 0 || m <= 0) return -1;
return n == 1 ? 0 : (LastRemaining_Solution(n - 1, m) + m) % n;
}
}