圆圈中最后剩下的数(约瑟夫环)

题目描述
约瑟夫问题是一个非常著名的趣题,即由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();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值