给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 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
求所有数量的最大公约数,然后判断是否大于2即可....之前走了太多弯路。
#include<iostream>
#include<unordered_map>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> m_map;
if (deck.empty()) {
return false;
}
bool hasGroup = true;
for (int i = 0; i < deck.size(); i++) {
if (m_map.count(deck[i]) == 0) {
m_map[deck[i]] = 1;
}
else {
m_map[deck[i]]++;
}
}
/* 算所有的val值的最大公约数是不是大于2,如果是说明满足,不是则说明不满足 */
unordered_map<int, int>::iterator it = m_map.begin();
int comVal = it->second;
int gcdNum = 0;
while (it != m_map.end()) {
if (it->second < 2) {
hasGroup = false;
break;
}
gcdNum = gcd(comVal, it->second);
comVal = gcdNum;
it++;
}
if (!hasGroup)
return false;
if (gcdNum < 2) {
hasGroup = false;
}
return hasGroup;
}
private:
/* 辗转相除法 */
int gcd(int x, int y) {
int z = y;
while (x % y != 0) {
z = x % y;
x = y;
y = z;
}
return z;
}
};