码迷,mamicode.com
首页 > 其他好文 > 详细

剑指OFFER 孩子们的游戏

时间:2020-02-03 19:12:01      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:怎么   ==   ack   class   cto   pre   push   ||   erase   

剑指OFFER 孩子们的游戏

本质上都是被点到孩子就出局,区别在于怎么表示出局这个状态

数组解法(复杂度高)

class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {
        if(n==0||m==0)return -1;
        if(n==1)return 0;

        int count = 0;
        int now = 0;
        int last_child = 0;
        vector<bool> childs;
        childs.resize(n,false);
        for(int i=0;count!=n;i++)
        {
            if(childs[i%n]==true)continue;
            now++;
            if(now == m)
            {
                childs[i%n]=true;
                now = 0;
                count++;
                last_child = i%n;
            }
        }
        return last_child;
    }
};

STL链表解法

class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {
        if(n==0||m==0)return -1;
        if(n==1)return 0;
        list<int> childs;
        int last_child = 0;
        int count = 0;
        int now = 0;

        for (int i = 0; i < n; i++)
        {
            childs.push_back(i);
        }

         auto it = childs.begin();
         while(count != n)
         {
             now++;
             if(now == m){
                 now = 0;
                 count++;
                 last_child = *it;
                 it = childs.erase(it);
                 if (it == childs.end())it = childs.begin();
                 continue;
             }
             it++;
             if(it == childs.end())it = childs.begin();
         }

        return last_child;
    }
};

剑指OFFER 孩子们的游戏

标签:怎么   ==   ack   class   cto   pre   push   ||   erase   

原文地址:https://www.cnblogs.com/virgildevil/p/12256696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!