leetcode 914. X of a Kind in a Deck of Cards 卡牌分组 多个数的最大公约数
leetcode 2020年3月 每日一题打卡
题目:
给定一副牌,每张牌上都写着一个整数。此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:每组都有 X 张牌。组内所有的牌上都写着相同的整数。仅当你可选的 X >= 2 时返回 true。
示例 1:输入:[1,2,3,4,4,3,2,1] 输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
示例 2:输入:[1,1,1,2,2,2,3,3] 输出:false
解释:没有满足要求的分组。
示例 3:输入:[1] 输出:false
解释:没有满足要求的分组。
示例 4:输入:[1,1] 输出:true
解释:可行的分组是 [1,1]
示例 5:输入:[1,1,2,2,2,2] 输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]
提示:
1 <= deck.length <= 10000
0 <= deck[i] < 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards
思路: 计数+求多个数的最大公约数。如何求多个数的最大公约数:根据数论中的gcd结合律知:gcd(a,b,c)=gcd(gcd(a,b),c)
时间复杂度:求最大公约数O(logC),外层循环N层,最终复杂度O(NlogC)。
代码:
class Solution(object):
def hasGroupsSizeX(self, deck):
"""
:type deck: List[int]
:rtype: bool
"""
def gcd(m,n):
return gcd(n,m%n) if n else m
# 计数排序
count = [0]*10000
for d in deck:
count[d]+=1
countset=list(set(count))
if len(countset)==1 and countset[0]>=2:
return True
#求多个数的最大公约数
ans=countset[0]
for i in range(1,len(countset)):
ans=gcd(ans,countset[i])
if ans>1:
return True
else:
return False