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

Coins in a Line

时间:2019-12-21 22:16:37      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:input   tle   Plan   eth   否则   NPU   body   证明   als   

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

标签:input   tle   Plan   eth   否则   NPU   body   证明   als   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078236.html

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