Coins in a Line

Description

There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.

Could you please decide the first player will win or lose?

If the first player wins, return true, otherwise return false.

Example

Example 1:

Input: 1
Output: true

Example 2:

Input: 4
Output: true
Explanation:
The first player takes 1 coin at first. Then there are 3 coins left.
Whether the second player takes 1 coin or two, then the first player can take all coin(s) left.

Challenge

O(n) time and O(1) memory

思路:

可以证明, 当硬币数目是3的倍数的时候, 先手玩家必败, 否则他必胜.

当硬币数目是3的倍数时, 每一轮先手者拿a个, 后手者拿3-a个即可, 后手必胜.

若不是3的倍数, 先手者可以拿1或2个, 此时剩余硬币个数就变成了3的倍数.

public class Solution {
    /**
     * @param n: An integer
     * @return: A boolean which equals to true if the first player will win
     */
    public boolean firstWillWin(int n) {
        if (n % 3 != 0)
            return true;
        else
            return false;
    }
}

  

 

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078236.html
今日推荐