Coins in a Line
Posted flagyuri
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于Coins in a Line的主要内容,如果未能解决你的问题,请参考以下文章