[leetCode]剑指 Offer 62. 圆圈中最后剩下的数字

解法一 环形链表

使用链表构造一个环,每个删除第m个数直到链表中剩下一个元素

class Solution {
    public int lastRemaining(int n, int m) {
        if (n < 1 || m < 1)
            return -1;
        LinkedList<Integer> numbers = new LinkedList<>();
        for (int i = 0; i < n; ++i) 
            numbers.offer(i);
        
        ListIterator<Integer> current = numbers.listIterator(0);

        while (numbers.size() > 1) {
            for (int i = 1; i < m; ++i) {
                current.next();
                if (!current.hasNext())
                    current = numbers.listIterator(0);
            }
            current.next();
            current.remove();
            if (!current.hasNext())
                current = numbers.listIterator(0);
            
        }
        return current.next();
    }
}

解法二 数学

官方题解

class Solution {
    public int lastRemaining(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;
    }
}
posted @ 2020-09-26 10:58  消灭猕猴桃  阅读(74)  评论(0编辑  收藏  举报