剑指Offer——约瑟夫环,0,1,...n-1围成的环,从0开始每次删除第m个,求最后剩余的一个数字

主要思路:

1.利用list容器循环,循环过程中判断一旦到达容器尾就将迭代器指向容器头

2.利用递推关系

f(n,m) = {  0                           n=1

             {  [f(n-1,m)+] % n      n>1      具体类推过程见剑指Offer面试题45


一下代码在vs2015中调试运行无误

#include "stdafx.h"
#include<iostream>
#include<list>

using namespace std;

int LastRemaining(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);
}

int lastRemaining(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;
}

int main()
{
	unsigned int n;
	unsigned int m;
	int result1,result2;
	cin >> n >> m;
	result1 = LastRemaining(n, m);
	result2 = lastRemaining(n, m);

	if ((-1 == result1) && (-1 == result2))
	{
		cout<<"Invialid Input!";
	}
	else 
	{
		cout << "the Lastremain is :	" << result1 << "\n"<<"the lastRemaining is:	"<< result2;
	}
	while (1);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值