参考别人的代码
方法一:链表模拟
import java.util.LinkedList; import java.util.List; public class Solution { public int LastRemaining_Solution(int n, int m) { if (n<=0 || m<=0) return -1; List<Integer> list=new LinkedList<>(); for (int i=0;i<n;i++) list.add(i); int p=0; while (list.size()>1){ p=(p+m-1)%list.size(); list.remove(p); } return list.get(0); } }
方法二:数学公式
f(N,M) = ( f(N−1,M) + M ) % N
public class Solution { public int LastRemaining_Solution(int n, int m) { if (n<=0 || m<=0) return -1; if (n==1) return 0; return (LastRemaining_Solution(n-1,m)+m)%n; } }
或
public class Solution { public int LastRemaining_Solution(int n, int m) { if (n<=0 || m<=0) return -1; int p=0; for (int i=2;i<=n;i++){ p=(p+m)%i; } return p; } }