zoukankan      html  css  js  c++  java
  • 剑指OFFER 孩子们的游戏

    剑指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;
        }
    };
    
  • 相关阅读:
    [pyqt4]mark
    EPC摘抄
    sockaddr struct 类型重定义
    linux编译警告 will be initialized after
    cout如何输出十六进制
    strcpy unsigned char
    c语言格式控制符
    c++字节数组转换为整型
    C++如何判断大小端
    C++中关于位域的概念
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12256696.html
Copyright © 2011-2022 走看看