模拟一个环形链表,当报数到m-1的时候,就将对应下标的移除链表,然后继续从0开始报数到m-1,继续移除,知道剩下一个为止

public int LastRemaining_Solution(int n, int m) {
         if(n < 1 || m < 1)
             return -1;
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0; i < n; i++)  list.add(i);

        int pre = 0;  /*从0开始*/
        while(list.size() > 1){
            pre = (pre+m-1)%list.size();   /*在前一个移除数的基础上,报m-1次,就是移除数的下标,用取模模拟环*/
            list.remove(pre);
        }
        return list.get(0);
    }

使用数学规律

public class Solution {
    public int LastRemaining_Solution(int n, int m) {
         if(n < 1 || m < 1)
             return -1;
        int last = 0;
        for(int i = 2; i <= n; i++){
            last = (last+m)%i;
        }
        return last;
    }
}