Article Directory
1. Source title
Links: 914. Card grouping
Source: LeetCode
2. Description title
3. resolve title
Method a: Method conventional analog + gcd +
Simple title, abstract need to understand, simply under the idea:
- You first need to be repeated the number of statistics, using
map
data structures can be directly statistics, the most convenient and effective. There is also an array using the count can. Of course,sort
post-processing is also possible, high time complexity. Many data processing method, non-key. - Count the number of repetitions to get all of the significant digits, then the packet
x
is any repetition of these non-convention a number 1 , because of this ready-madegcd
greatest common divisor method to be used directly, and with the efficiency of internal division is also removed High. May also seek to enumerate the number of conventions through violence, the time complexity is higher.
See the code below:
// 执行用时 :44 ms, 在所有 C++ 提交中击败了6.40%的用户
// 内存消耗 :16.9 MB, 在所有 C++ 提交中击败了5.71%的用户
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
map<int, int> m;
for (int i = 0; i < deck.size(); i++)
m[deck[i]]++;
int g = m.begin()->second;
for (auto i = m.begin(); i != m.end(); i++)
g = gcd(g, i->second);
return g >= 2;
}
};
// 简约风
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
map<int, int> m;
for (auto& e : deck) m[e]++;
int g = m.begin()->second;
for (auto& e : m) g = gcd(g, e.second);
return g >= 2;
}
};