LeetCode.剑指offer.062.圆圈中最后剩下的数字/约瑟夫环
题目描述
《剑指offer》面试题62. 圆圈中最后剩下的数字
https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/
0,1,,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。
例如,0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。
示例 1:
输入: n = 5, m = 3
输出: 3
示例 2:
输入: n = 10, m = 17
输出: 2
限制:
1 <= n <= 10^5
1 <= m <= 10^6
解题过程
暴力模拟法
用一个数组模拟 0,…,n-1 个数,每次从中删除第m个,不断循环直到数组长度为1
时间复杂度 O(mn),一共需要删除n-1个数,每次从数组删除一个元素的时间复杂度是 O(n)
空间复杂度 O(n)
private static class SolutionV2020 {
    public int lastRemaining(int n, int m) {
        ArrayList<Integer> arrayList = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            arrayList.add(i);
        }
        int idx = 0;
        while (arrayList.size() > 1) {
            idx = (idx + m - 1) % arrayList.size();
            arrayList.remove(idx);
        }
        return arrayList.get(0);
    }
}
数学递推
GitHub代码
algorithms/leetcode/offer/_062_JosephusProblem.java
https://github.com/masikkk/algorithms/blob/master/leetcode/offer/_062_JosephusProblem.java
上一篇 LeetCode.912.Sort an Array 排序数组
下一篇 LeetCode.1162.As Far from Land as Possible 离所有陆地最远的海洋/地图分析
页面信息
location:protocol: host: hostname: origin: pathname: href: document:referrer: navigator:platform: userAgent: