publicintLastRemaining_Solution(int n, int m){ if (n <= 0 || m <= 0) { return -1; } int target = m - 1; int[] childens = newint[n]; for (int i = 0; i < n; i ++) { childens[i] = i + 1; } childens[n - 1] = 0; int preIndex = 0; int index = 0; int cnt = 0; while (childens[index] != index) { cnt ++; preIndex = index; index = childens[index]; if (cnt == target) { childens[preIndex] = childens[index]; index = childens[index]; cnt = 0; } } return index; }
publicstaticvoidmain(String[] args){ int n = 7, m = 3; Solution s = new Solution(); System.out.println(s.LastRemaining_Solution(n, m)); } }