题目描述
每年六一儿童节,NowCoder都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为NowCoder的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到NowCoder名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?
感想:这种题一看就想的到申请n个容器/数组,删除直到剩下一个数。但是这么做的缺点是空间复杂度很高O(n),没删除一个数循环m次,共要删除n-1个数,所以时间复杂度是O(mn)。这种方法肯定有一种数学上的规律总结,剑指上也有写,但是看不大理解。实际编写是照前面方法写的。
实现时候的问题:参考剑指Offer的写法,一直容易报“vector iterator not incrementable‘错误。因为erase之后迭代器会失效,直接用新声明的temp来接erase的返回值,即只想current的下一个指针,没有错误了。
圆圈的最后一个数
#include <iostream>
#include <vector>
using namespace std;
int LastRemaining_Solution(unsigned int n, unsigned int m)
{
if(n<=0||m<=0)
return -1;
vector<int> v;
for(int i=0;i<n;i++)
v.push_back(i);
vector<int>::iterator current=v.begin();
while(v.size()>1)
{
for(int i=1;i<m;i++)
{
current++;
if(current==v.end())
current=v.begin();
}
/*vector<int>::iterator temp=++current;
if(temp==v.end())
temp=v.begin();
--current;
temp=v.erase(current);
current=temp;*/
vector<int>::iterator temp=v.erase(current);
if(temp==v.end())
temp=v.begin();
current=temp;
}
return *current;
}
void main()
{
cout<<LastRemaining_Solution(100,5);
system("pause");
}