约瑟夫问题(剑指offer)

题目描述

每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

解题思路

最直观的方法是直接模拟,复盘整个转圈的过程。其中可以用求余来表示转圈。注意new出来的动态数组大小不可以用sizeof来得到,sizeof得到的动态数组长度是指针的大小。

class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {
        if(n==0) return -1;
        bool *a = new bool[n];
        memset(a,false,n);
        int childcount = n,curpos = -1 ;
        while(childcount>=1){
            int count = m;
            while(count--){
                curpos++;
                while(a[curpos%n]) curpos++;
            }
            a[curpos%n] = true;
            childcount-=1;
            if(childcount==1) {
                while(a[curpos%n]) curpos++;
                return curpos%n;
            }
        }
        return curpos%n;
    }
};

改进的话还可以使用链表去完成,效率上会更快(17ms,上述解法288ms)。

class Solution {
public:
    class Node{
    public:
        int val;
        Node* next = NULL;
    };
    int LastRemaining_Solution(int n, int m)
    {
        if(n==0||m==0) return -1;
        Node* head = new Node;
        head->val = 0;
        Node* prenode = head;
        for(int i=1;i<n;i++){
            Node *tmp = new Node;
            tmp->val = i;
            prenode->next = tmp;
            prenode = tmp;
        }
        prenode->next = head;
        int childcount = n;
        Node* cur_pos = head,*pre_pos = NULL;
        while(childcount>1){
            for(int i=0;i<m-1;i++){
                if(cur_pos == NULL) cur_pos = head;
                else {
                    pre_pos = cur_pos;
                    cur_pos = cur_pos->next;
                }
            }
            pre_pos->next = cur_pos->next;
            cur_pos = pre_pos->next;
            childcount--;
        }
        return cur_pos->val;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值