LinkedList模拟约瑟夫环
孩子们的游戏(圆圈中最后剩下的数)
http://www.nowcoder.com/questionTerminal/f78a359491e64a50bce2d89cff857eb6
比如n=5, m=3
关键在于不要让m=0,1,2,0,1,2,...这样循环:
n: 0,1,2,3,4,5
m: 0,1,2,0,1,2
可以直接跳着来:
n: 0,1,2,3,4,5
m: 0, ,2, ,4,
import java.util.*; public class Solution { public int LastRemaining_Solution(int n, int m) { if(n<=0) return -1; LinkedList<Integer> container = new LinkedList<>(); for(int i=0;i<n;++i){ container.add(i); } int idx = 0; while(container.size()>1){ idx = (idx+(m-1))%container.size(); container.remove(idx); } return container.get(0); } }