题目描述
约瑟夫问题是一个非常著名的趣题,即由n个人坐成一圈,按顺时针由1开始给他们编号。然后由第一个人开始报数,数到m的人出局。现在需要求的是最后一个出局的人的编号。
给定两个int n和m,代表游戏的人数。请返回最后一个出局的人的编号。保证n和m小于等于1000。
测试样例:
5 3
返回:4
class Joseph {
public:
int getResult(int n, int m) {
// write code here
int last = 0;
for(int i = 2; i <= n; i++)
last = (last + m) % i;
return last + 1;
}
};
class Joseph {
public:
struct node
{
int no;
node *next;
};
int getResult(int n, int m) {
// write code here
node *head=new node;
head->no=n-1;
head->next=NULL;
node *tail=head;//保留最后一个位置的节点一边将链表头尾连接
for(int i=n-2; i>=0; i--)
{
node *p=new node;
p->no=i;
p->next=head;
head=p;
}
tail->next=head;
node *pre=tail;//保存被选中的节点前一个以便删去节点后重新连接链表
while(head->next!=head)//判断条件是链表中只剩一个节点才停下
{
node *tmp=head;
for(int i=0; i<m-1; i++)
{
tmp=tmp->next;
pre=pre->next;
}
pre->next=tmp->next;
head=pre->next;
delete tmp;
}
return pre->no+1;
}
};
链接:https://www.nowcoder.com/questionTerminal/11b018d042444d4d9ca4914c7b84a968
来源:牛客网
class Joseph {
public:
int getResult(int n, int m) {
list<int> circle;
// 初始状况
for(int i = 1;i <= n;++i){
circle.push_back(i);
}//for
list<int>::iterator cur = circle.begin();
while(circle.size() > 1){
// 数到m的人出局
for(int i = 0;i < m - 1;++i){
++cur;
if(cur == circle.end()){
cur = circle.begin();
}//if
}// for
// 因为删除数到m的人要记录下一个人的地址
list<int>::iterator next = ++cur;
if(next == circle.end()){
next = circle.begin();
}//if
--cur;
// 删除数到m的人
circle.erase(cur);
// 从下一个人继续开始
cur = next;
}//while
return circle.front();
}
};