LeetCode846 一手顺子

LeetCode846 一手顺子

哈希算法,count字典记录每个元素出现个数,然后按顺子规则逐个消减,判定是否符合

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:

        count, l = {}, len(hand)
        if l % groupSize != 0: return False
        
        for i in range(l):
            if hand[i] in count: count[hand[i]] += 1
            else: count[hand[i]] = 1
        
        hand.sort()
        for i in range(l):
            if count[hand[i]] == 0: continue
            else:
                for j in range(groupSize):
                    if (hand[i] + j) not in count or count[hand[i] + j] == 0: return False
                    count[hand[i] + j] -= 1
        return True

posted on 2022-07-01 22:02  solvit  阅读(12)  评论(0编辑  收藏  举报

导航