Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.
∙ 1 <= hand.length <= 104
∙ 0 <= hand[i] <= 109
∙ 1 <= groupSize <= hand.length
실패
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if groupSize == 1:
return True
# if groupSize >= len(hand):
# return T
a = list(combinations([2, 1], 2))
print(a)
combi = list(combinations(hand, groupSize))
print(combi)
start = combi[0][0]
c = 1
for i in range(1, len(combi)):
if combi[i][0] != start:
start = combi[i][0]
c += 1
if c == groupSize:
return True
return False
힙 자료구조 내장함수 사용
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
count = collections.Counter(hand)
minH = list(count.keys())
# heapq.heapify(x) -> x를 힙 자료형으로 변환
# heapq.heappush(x, y) -> x 힙에 y를 추가
# heapq.heappop(x) -> x 힙의 가장 작은 원소를 pop하고 리턴
heapq.heapify(minH) # 힙이 되지만 순서는 유지된다.
while minH:
first = minH[0]
for i in range(first, first + groupSize):
if i not in count:
return False
count[i] -= 1
if count[i] == 0:
if i != minH[0]:
return False
heapq.heappop(minH)
return True