孩子们的游戏(圆圈中最后剩下的数)
- 参与人数:1828时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
每年六一儿童节,NowCoder都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为NowCoder的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到NowCoder名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?
既然题目中有一个数字圆圈,很自然的想法就是用一个数据结构来模拟这个圆圈。在常用的数据结构中,我们很容易想到环形链表。我们可以创建一个总共有N个节点的环形链表,然后每次在这个链表中删除第m个节点。
同时我们可以用std::list来模拟环形链表,std::list的最后一个元素是哨兵,并不包含实际的数据,只是标记链表结尾,当迭代器扫描到std::list末尾时我们要记得把迭代器移到链表头部。
// 43.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <list>
using namespace::std;
class Solution {
public:
int LastRemaining_Solution(unsigned int n, unsigned int m) {
if (n < 1 || m < 1) return -1;
list<int> li;
for (int i = 0; i < n; i++) {
li.push_back(i);
}
list<int>::iterator cur = li.begin();
while (li.size() > 1) {
for (int i = 1; i < m; i++) {
++cur;
if (cur == li.end())
cur = li.begin();
}
list<int>::iterator next = ++cur;
if (next == li.end())
next = li.begin();
li.erase(--cur);
cur = next;
}
return (*cur);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution s;
s.LastRemaining_Solution(5, 3);
return 0;
}
第二次做:
一开始用的vector,但是我忘了vector 的重要性质:元素在内存里连续存放,我们不能动态的删除vector里面的元素,不然会报断言错误,要动态删元素,首选list
// 孩子们的游戏(圆圈中最后剩下的数).cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <list>
using namespace::std;
class Solution {
public:
int LastRemaining_Solution(unsigned int n, unsigned int m) {
if (n < 1 || m < 1) return -1 ;
list<int> arr ;
for (int i = 0; i < n; ++i) {
arr.push_back(i) ;
}
list<int>::iterator cur = arr.begin() ;
while (arr.size() > 1) {
for (int i = 1; i < m; ++i) {
++cur ;
if (cur == arr.end()) cur = arr.begin() ;
}
list<int>::iterator next = ++cur ;
if (next == arr.end()) next = arr.begin() ;
--cur ;
arr.erase(cur) ;
cur = next ;
}
return (*cur) ;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution s;
s.LastRemaining_Solution(5, 3);
return 0;
}
第三次做:
class Solution {
public:
int LastRemaining_Solution(unsigned int n, unsigned int m) {
if ( n <= 0 || m <= 0 ) return -1 ;
list<int> loop ;
for ( int i = 0; i < n; ++ i ) {
loop.push_back( i ) ;
}
list<int>::iterator cur = loop.begin() ;
while ( loop.size() > 1 ) {
for ( int i = 1; i < m; ++ i ) {
++ cur ;
if ( cur == loop.end() ) cur = loop.begin() ;
}
list<int>::iterator wait_to_delete = cur ;
++ cur ;
if ( cur == loop.end() ) cur = loop.begin() ;
loop.erase( wait_to_delete ) ;
}
return ( *cur ) ;
}
};