leetcode 914. X of a Kind in a Deck of Cards

本文介绍了一个使用C++实现的算法,该算法通过遍历和模运算判断一副牌(整数数组)是否可以分成大小相等的组,每组包含的每个元素数量相同。算法首先统计每张牌出现的次数,然后检查这些次数是否都能被可能的组大小整除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<algorithm>
#include<map>
class Solution {
public:

    bool hasGroupsSizeX(vector<int>& deck) {
        int l = deck.size();
        if(l<2)return false;
        map<int,int> num;
        for(int i=0;i<l;i++)
        {
             num[deck[i]]++;
        }
        
       for(int x=2;x<=l;x++)
        {
            if(l%x!=0)continue;
            else
            {   map<int,int>::iterator it;
                bool all =true;
                for(it=num.begin();it!=num.end();it++)
                {
                    cout<<it->first<<" "<<it->second<<" ";
                    if(it->second%x!=0)
                    {
                        all = false;
                        break;
                    }
                    
                }
                cout<<endl;
                if(all)return true;
            }
        }
        return false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值