在给定 hand 的情况下,划分方式唯一确定,因此本质上这是一个「模拟」的过程 先统计每个数字频率map,维护一个小根堆,每次取堆顶数字t,尝试作为顺子的起点,看[t, t+1,..., t+m-1]
共m个数是否还有剩(即在map中频率>0),就将其取出,同时更新map
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
p = []
heapq.heapify(p) #建堆
map = {}
for i in hand: #统计每个数字频率
map[i] = map.get(i, 0) + 1
heapq.heappush(p, i)
while p:
t = heapq.heappop(p) # 取堆顶(最小的数)
if map[t] == 0: #该数已用完,跳过
continue
for i in range(groupSize): #尝试取t ~ t+m-1
cnt = map.get(t+i, 0)
if cnt == 0: #数量为0,无法构成顺子
return False
map[t+i] = cnt-1
return True