LeetCode 846. 一手顺子(C++、python)

爱丽丝有一手(hand)由整数数组给定的牌。 

现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。

如果她可以完成分组就返回 true,否则返回 false

 

示例 1:

输入:hand = [1,2,3,6,2,3,4,7,8], W = 3
输出:true
解释:爱丽丝的手牌可以被重新排列为 [1,2,3],[2,3,4],[6,7,8]

示例 2:

输入:hand = [1,2,3,4,5], W = 4
输出:false
解释:爱丽丝的手牌无法被重新排列成几个大小为 4 的组。

 

提示:

1 <= hand.length <= 10000

0 <= hand[i] <= 10^9

1 <= W <= hand.length

C++

class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int W) 
    {
        int n=hand.size();
        if(0!=n%W)
        {
            return false;
        }
        if(1==W)
        {
            return true;
        }
        sort(hand.begin(),hand.end());
        map<int,int> tmp;
        for(int i=0;i<n;i++)
        {
            tmp[hand[i]]++;
        }
        map<int,int>::iterator it;
        for(it=tmp.begin();it!=tmp.end();it++)
        {
            int count=it->second;
            if(count>0)
            {
                for(int i=0;i<W;i++)
                {
                    tmp[it->first+i]-=count;
                    if(tmp[it->first+i]<0)
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }
};

python

class Solution:
    def isNStraightHand(self, hand, W):
        """
        :type hand: List[int]
        :type W: int
        :rtype: bool
        """
        n=len(hand)
        if n%W!=0:
            return False
        hand.sort()
        tmp=collections.Counter(hand)
        for key in tmp:
            if tmp[key]>0:
                count=tmp[key]
                for i in range(W):
                    tmp[key+i]-=count
                    if tmp[key+i]<0:
                        return False
        return True
             
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值