剑指Offer,约瑟夫环,圆圈中最后剩下的数字

题目:

思路:
https://leetcode.cn/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solutions/177639/javajie-jue-yue-se-fu-huan-wen-ti-gao-su-ni-wei-sh/

    public int lastRemaining(int n, int m) {
        ArrayList<Integer> list = new ArrayList<>();

        for (int i=0;i<n;i++) {
            list.add(i);
        }

        int idx = 0;

        while (n > 1) {
            idx = (idx + m - 1) % n;  // 注意,这里-1 ,是因为idx所在位置删除后,在list中会往前窜一位,所以这里下个删除的位置时间是idx+m-1
            list.remove(idx);
            n--;
        }

        return list.get(0);
    }

你可能感兴趣的:(leetcode)