zl程序教程

您现在的位置是:首页 >  其它

当前栏目

菜鸟的每日力扣系列——846. 一手顺子

系列 每日 菜鸟 力扣 一手 顺子
2023-06-13 09:15:51 时间

拿到题我们看,首先要把牌分成n组,那么数组中元素个数必须能被n整除,即len(hand) % groupsize = 0;分组问题有了思路之后就是重新排列,我们知道,如果是顺子的话,需要连续的自然数,可以使用哈希表来统计hand中不同数字的数量,循环groupsize次,每次从剩余牌中找到数字最小的那个设为k,然后将哈希表中[k, k+groupsize)的每个数数量减一,如果数量不足一,表示缺少这张牌,并不能组成顺子,也就不能分成有效的groupsize组。

from typing import List
from collections import Counter

def isNStraightHand(hand: List, groupSize: int) -> bool:
    if len(hand) % groupSize != 0:
        return False
    cnt = Counter(hand)
    hand = sorted(set(hand), reverse=True)
    for _ in range(len(hand) // groupSize):
        k, v = hand[-1], cnt[hand[-1]]
        for i in range(k, k + groupSize):
            if cnt[i] < v:
                return False
            cnt[i] -= v
        while hand and not cnt[hand[-1]]:
            hand.pop()
    return True

# hand = [1,2,3,6,2,3,4,7,8]
# groupSize = 3  # True
hand = [1,2,3,4,5]
groupSize = 4  # False
print(isNStraightHand(hand, groupSize))

(明天除了菜鸟的每日一题外,还想分享一下这一年的我的经历和收获,预感会有很多要说的~期待一下,明天见。)

END