Alice has a
hand
of cards, given as an array of integers.Now she wants to rearrange the cards into groups so that each group is size
W
, and consists ofW
consecutive cards.Return
true
if and only if she can.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Explanation: Alice'shand
can be rearranged as[1,2,3],[2,3,4],[6,7,8]
.Example 2:
Input: hand = [1,2,3,4,5], W = 4 Output: false Explanation: Alice'shand
can't be rearranged into groups of4
.
题目要求卡牌数能平分成每份W张牌,且每份都是连续的数
1 my solution
刚开始很容易就想到count,但是由于我不想用额外空间,所以直接sort 遍历,一共有len / W 份
记turn = len /W
每轮w张牌都满足连续条件的话就删掉,所以hand[0]永远是最小的,所以每份W张都是 hand[0],hand[0]+1,...,hand[0]+W-1
class Solution:
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
if len(hand) % W !=0: return False
turn = len(hand) / W
hand.sort()
while(turn >0 ):
a = hand[0]
for i in range(1,W):
if a+i not in hand:return False
else:del hand[hand.index(a+i)]
del hand[hand.index(a)]
turn -= 1
return True
2 暴力破解
class Solution:
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
count = collections.Counter(hand)
if sum(list(count.values())) % W !=0:return False
while count:
minx = min(count)
for i in range(1,W):
if not count.get(minx + i):return False
else:
count[minx + i] -= 1
if count[minx + i] == 0:del count[minx + i]
count[minx] -= 1
if count[minx] == 0:del count[minx]
return len(count) == 0