• 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
  • 相关阅读:
    BestCoder Round #32
    USACO Runaround Numbers
    USACO Subset Sums
    USACO Sorting a Three-Valued Sequence
    USACO Ordered Fractions
    USACO 2.1 The Castle
    Codeforces Round #252 (Div. 2)
    Codeforces Round #292 (Div. 2)
    BZOJ 1604: [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居
    BZOJ 1603: [Usaco2008 Oct]打谷机
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13308323.html
Copyright © 2020-2023  润新知