题解 | #孩子们的游戏(圆圈中最后剩下的数)#
孩子们的游戏(圆圈中最后剩下的数)
http://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6
import java.util.*; public class Solution { public int LastRemaining_Solution(int n, int m) { // 0 1 2 3 4 // 0 1 3 4 // 1 3 4 // 1 3 // 3 if(m == 0 || n == 0){ return -1; } ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i < n; ++i){ list.add(i); } fun(list, 0, m); return list.get(0); } public static void fun(ArrayList<Integer> list, int start, int m){ if(list.size() == 1){ return; } int pos = (start + m - 1) % list.size(); int nextPos = 0; if(pos == list.size() - 1){ nextPos = 0; }else{ nextPos = pos; } list.remove(list.get(pos)); fun(list, nextPos, m); } }