914. X of a Kind in a Deck of Cards (easy)
In a deck of cards, each card has an integer written on it.
Return
true
if and only if you can chooseX >= 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.
Example 1:
Input: [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
Example 2:
Input: [1,1,1,2,2,2,3,3] Output: false Explanation: No possible partition.
Example 3:
Input: [1] Output: false Explanation: No possible partition.
Example 4:
Input: [1,1] Output: true Explanation: Possible partition [1,1]
Example 5:
Input: [1,1,2,2,2,2] Output: true Explanation: Possible partition [1,1],[2,2],[2,2]
1 暴力破解(其实very fast Or2
Runtime: 44 ms, faster than 99.67% of Python3
class Solution(object):
def hasGroupsSizeX(self, deck):
count = collections.Counter(deck)
N = len(deck)
for X in range(2, N+1):
if N % X == 0:
if all(v % X == 0 for v in count.values()):
return True
return False
2 awkard & stupid me
思路:用存在公倍数求解
e.g.[1,2,3,4,4,3,2,1] ->set = [1,2,3,4] 每个数在deck的count都是2个,公倍数都是2 -》true
e.g.[1,1,1,2,2,2,3,3] -》set = [1,2,3] 每个数在deck的count分别为3,3,2,不存在相同的公倍数 -》false
我的笨办法求相同的公倍数,先求set里第一个数的count(即deck.count(set[0]))的公倍数list(所有公倍数):gbs
遍历set的其他数,如果gbs里的数不是遍历到的这个数count的公倍数 则移除
最后剩下的gbs是所有数count的共同公倍数
class Solution:
def hasGroupsSizeX(self, deck):
"""
:type deck: List[int]
:rtype: bool
"""
setdeck = list(set(deck))
if len(deck) < 2 or deck.count(setdeck[0]) == 1:return False
gbs = []
for i in range(2,deck.count(setdeck[0])+1):
if deck.count(setdeck[0]) % i == 0:
gbs.append(i)
for x in setdeck:
num = deck.count(x)
aa = gbs.copy()
for gb in aa:
if num% gb != 0:gbs.remove(gb)
return True if len(gbs) >= 1 else False
1528ms 0.99% Or2
3 结合改进(fast
每一个循环都计算count很耗时,发现collections.count先把所有数字出现的次数计算了,return一个字典dict{数字:次数}
class Solution:
def hasGroupsSizeX(self, deck):
"""
:type deck: List[int]
:rtype: bool
"""
count = collections.Counter(deck)
setdeck = list(set(deck))
if len(deck) < 2 or deck.count(setdeck[0]) == 1:return False
gbs = []
for i in range(2,count[setdeck[0]]+1):
if count[setdeck[0]]% i == 0:gbs.append(i)
for x in setdeck:
aa = gbs.copy()
for a in aa:
if count[x]%a !=0:gbs.remove(a)
return True if len(gbs)>=1 else False
Runtime: 44 ms, faster than 99.67% of Python3