【python3】leetcode 914. X of a Kind in a Deck of Cards (easy)
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