主要思路:
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;
}