914. X of a Kind in a Deck of Cards

In a deck of cards, each card has an integer written on it.

Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

  • Each group has exactly X cards.
  • All the cards in each group have the same integer.

问能不能把排分成n组,每组的牌卡片数量X大于等于2,每组的牌必须是相同值。

统计每个值出现的次数,能不能分成n组使得每组卡牌数量大于2,这个就是想求一下每个值出现次数的最大公约数是否大于等于2

比如[1,1,1,1,2,2]1出现4次2出现2次,最大公约数是2,因此可以分成2张一组的,[1,1,1,2,2]1出现次数是3,2出现次数是2,最大公约数是1,因此只能分成1张一组的。

class Solution(object):
    def hasGroupsSizeX(self, deck):
        """
        :type deck: List[int]
        :rtype: bool
        """
        def gcd(a, b):
            return b if a == 0 else gcd(b % a, a) 
        d = {}
        for value in deck:
            if value in d:
                d[value] += 1
            else:
                d[value] = 1
        g = None
        for key, value in d.items():
            if g is None:
                g = value
            else:
                g = gcd(g, value)
        return g >= 2

 

posted @ 2020-07-15 21:43  whatyouthink  阅读(129)  评论(0编辑  收藏  举报