问题描述
给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。
示例 1:
输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
示例 2:
输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。
示例 3:
输入:[1]
输出:false
解释:没有满足要求的分组。
示例 4:
输入:[1,1]
输出:true
解释:可行的分组是 [1,1]
示例 5:
输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]
提示:
1 <= deck.length <= 10000
0 <= deck[i] < 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果
代码描述
思路:将所有的卡牌,放进map<key, val> group数组,val 存储 key的次数。然后求所有val 的公约数。存在则返回true,否则,返回false。注意如果[1,1,1,1,1,1], 会返回true. 感觉map 比较费时。
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
if(deck.size() < 2) return false;
map<int, int> group;
// 生成map
for(int i = 0; i < deck.size(); ++i)
{
if(group.count(deck[i]) == 0)
group.insert(make_pair(deck[i], 1));
else
group[deck[i]]++;
}
// 查找最大值
map<int, int>::const_iterator it = group.begin();
int Max = 0;
while(it != group.end())
{
Max>it->second ? Max : Max = it->second;
++it;
}
// 处理公约数
int j = 2;
int count = 0;
it = group.begin();
while(j <= Max)
{
for(; it != group.end(); ++it)
{
if(it->second % j == 0)
++count;
}
if(count == group.size()) return true;
count = 0;
it = group.begin();
++j;
}
return false;
}
};