給定一副牌,每張牌上都寫着一個整數。
此時,你需要選定一個數字 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;
}
};