// 面试题62:圆圈中最后剩下的数字
// 题目:0, 1, …, n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里
// 删除第m个数字。求出这个圆圈里剩下的最后一个数字。 #include <iostream>
#include <list> using namespace std; // ====================方法1====================
//使用环形链表
int LastRemaining_Solution1(unsigned int n, unsigned int m)
{
if (n < || m < )//边界判断
return -; unsigned int i = ; list<int> numbers;//建立一个链表,值为0~n
for (i = ; i < n; ++i)
numbers.push_back(i); list<int>::iterator current = numbers.begin();//设置迭代器
while (numbers.size() > )
{
for (int i = ; 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);//上面循环完就剩一个了
} // ====================方法2====================
//需要严谨的数学公式推导,最终得到如下的公式
int LastRemaining_Solution2(unsigned int n, unsigned int m)
{
if (n < || m < )
return -; int last = ;
for (int i = ; i <= n; i++)
last = (last + m) % i; return last;
} // ====================测试代码====================
void Test(const char* testName, unsigned int n, unsigned int m, int expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName); if (LastRemaining_Solution1(n, m) == expected)
printf("Solution1 passed.\n");
else
printf("Solution1 failed.\n"); if (LastRemaining_Solution2(n, m) == expected)
printf("Solution2 passed.\n");
else
printf("Solution2 failed.\n"); printf("\n");
} void Test1()
{
Test("Test1", , , );
} void Test2()
{
Test("Test2", , , );
} void Test3()
{
Test("Test3", , , );
} void Test4()
{
Test("Test4", , , );
} void Test5()
{
Test("Test5", , , -);
} void Test6()
{
Test("Test6", , , );
} int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
system("pause");
return ;
}