Leetcode846 一手顺子

分析

开始首先判断,如果hand数组大小不能整除W,说明不能均分成组,直接返回false。
之后对数组进行排序。并计算总的组数len。
设一个a[]记录该数组当前最大数,cnt[]记录当前数组大小。
之后对每一个元素能否放入当前组进行判断,若最终该元素无处安放,直接返回false。

C++ 代码

class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int W) {
        int n=hand.size();
        if(n%W!=0 || n<1) return false;
        sort(hand.begin(),hand.end());
        int len=n/W;
        int a[len+1],cnt[len+1];
        memset(a,-1,sizeof a);
        memset(cnt,0,sizeof cnt);
        for(int i=0;i<n;i++)
        {
            int idx=0,f=0;
            while(idx<len)
            {
                if(a[idx]==-1)  //当前数组为空,可以放
                {
                    a[idx]=hand[i],cnt[idx]++;
                    f=1;
                    break;
                }
                else{
                    if(hand[i]-1==a[idx] && cnt[idx]<W) //可以形成连续数组且大小小于W,可以放
                    {
                        a[idx]=hand[i],cnt[idx]++;
                        f=1;
                        break;
                    }
                }
                idx++;
            }
            if(!f) return false;    //无处安放,直接返回false
        }
        for(int i=0;i<len;i++)
        {
            if(cnt[i]!=W) return false; //该组没有连续W张牌,返回false
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/Jay_fearless/article/details/112709494