390 Elimination Game 淘汰游戏

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了390 Elimination Game 淘汰游戏相关的知识,希望对你有一定的参考价值。

详见: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 淘汰游戏的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 390. Elimination Game

Leetcode 390. Elimination Game

390. Elimination Game

leetcode390. Elimination Game

390. 消除游戏

Egret 之 消除游戏 开发 PART 6 Egret elimination game development PART 6