Leetcode 914.卡牌分组(X of a Kind in a Deck of Cards)

Leetcode 914.卡牌分组

1 题目描述(Leetcode题目链接

  给定一副牌,每张牌上都写着一个整数。此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:

  • 每组都有 X 张牌。
  • 组内所有的牌上都写着相同的整数。
  • 仅当你可选的 X >= 2 时返回 true。
输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1][2,2][3,3][4,4]
输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。
输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1][2,2][2,2]

提示:

  • 1 <= deck.length <= 10000
  • 0 <= deck[i] < 10000

2 题解

  先计数,然后看这些数的最大公约数是否大于等于2。

class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        length = len(deck)
        d = {}
        for i in range(length):
            if deck[i] not in d:
                d[deck[i]] = 1
            else:
                d[deck[i]] += 1
        return reduce(math.gcd, d.values()) >= 2
发布了263 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/105135001