zoukankan      html  css  js  c++  java
  • 剑指Offer——圆圈中最后剩下的数(约瑟夫环)

    Question

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

    Solution

    • 这道题我知道的有两种解法,一种是模拟,一种是递推关系。

    1. 模拟

    • 成环,然后又需要删除节点,这个时候我们应该想到用循环链表。实现循环链表,我们可以自己实现相应的数据结构,也可以用STL的list顺序链表容器来模拟,唯一的问题就在于,如果指针走到最后的时候,需要回到开始节点。

    2. 递推

    Code

    class Solution {
    public:
        int LastRemaining_Solution(int n, int m)
        {
            // 用链表进行模拟
            if (n < 1 || m < 1)
                return -1;
            
            list<int> nodes;
            for (int i = 0; i < n; i++)
                nodes.push_back(i);
            
            list<int>::iterator iter = nodes.begin();
            while (nodes.size() > 1) {
                
                // 数m,只需要移动m-1次
                for (int i = 1; i < m; i++) {
                    iter++;
                    if (iter == nodes.end())
                        iter = nodes.begin();
                }
                
                list<int>::iterator next = ++iter;
                if (next == nodes.end())
                    next = nodes.begin();
                
                --iter;
                nodes.erase(iter);
                
                iter = next;
            }
            
            return (*iter);
        }
    };
    

    参考文献

    STL list容器总结

  • 相关阅读:
    python的数据类型+常用操作符
    厉害了
    git merge ignore line ending
    CNAME , DNS , A Record , Domain Name

    setcookie无效
    magic quote gpc htmlspecialchars
    整型 浮点型 不能转化
    git push -f带来的conflict如何解决
    git pull --rebase
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7100464.html
Copyright © 2011-2022 走看看