62 圆圈中最后剩下的数字

题目

0,1,2...n-1这n个数字拍成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字,求剩下的最后一个数字。

例如0,1,2,3,4这5个数字组成的圈,每次删除第3个数字,一次删除2,0,4,1,因此最后剩下的是3。

** AcWing OJ**

C++ 题解

解法一

经典的解法, 用环形链表模拟圆圈。
创建一个总共有n 个结点的环形链表,然后每次在这个链表中删除第m 个结点。

int LastRemaining_Solution1(unsigned int n, unsigned int m)
{
	if (n < 1 || m < 1)
		return -1;

	unsigned int i = 0;

	list<int> numbers;
	for (i = 0; i < n; ++i)
		numbers.push_back(i);

	list<int>::iterator current = numbers.begin();

	while (numbers.size() > 1)
	{
		for (int i = 1; i < m; ++i)
		{
			current++;
			if (current == numbers.end())
				current = numbers.begin();
		}

		list<int>::iterator next = ++current;
		if (next == numbers.end())
			next = numbers.begin();

		--current;
		numbers.erase(current);
		current = next;
	}

	return *(current);
}

解法二

递推公式:
\(f(n, m)=\left\{\begin{array}{ll}{0} & {n=1} \\ {[f(n-1, m)+m] \% m} & {n>1}\end{array}\right.\)

int LastRemaining_Solution2(unsigned int n, unsigned 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;
}

python 题解

# -*- coding:utf-8 -*-
class Solution:
    def lastRemaining(self, n, m):
        # write code here
        if n<1 or m<1:
            return -1
        res=0
        for i in range(2,n+1):
            res=(res+m)%i
        return res
posted @ 2019-03-17 21:08  youngliu91  阅读(95)  评论(0编辑  收藏  举报