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

390 Elimination Game 淘汰游戏

时间:2018-04-15 21:46:53      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:lse   break   des   min   solution   nbsp   www   desc   tps   

详见:https://leetcode.com/problems/elimination-game/description/

C++:

方法一:

class Solution {
public:
    int lastRemaining(int n) {
        return help(n, true);    
    }
    int help(int n, bool left2right)
    {
        if (n == 1)
        {
            return 1;
        }
        if (left2right)
        {
            return 2 * help(n / 2, false);
        } 
        else
        {
            return 2 * help(n / 2, true) - 1 + n % 2;
        }
    }
};

方法二:

class Solution {
public:
    int lastRemaining(int n) {
        return n==1?1:2*(1+n/2-lastRemaining(n/2));
    }
};

 方法三:

class Solution {
public:
    int lastRemaining(int n) {
        int base = 1, res = 1;
        while (base * 2 <= n) 
        {
            res += base;
            base *= 2;
            if (base * 2 > n)
            {
                break;
            }
            if ((n / base) % 2 == 1)
            {
                res += base;
            }
            base *= 2;
        }
        return res;
    }
};

  详见:https://www.cnblogs.com/grandyang/p/5860706.html

390 Elimination Game 淘汰游戏

标签:lse   break   des   min   solution   nbsp   www   desc   tps   

原文地址:https://www.cnblogs.com/xidian2014/p/8849486.html

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