# 914. X of a Kind in a Deck of Cards 卡牌分组

@TOC

## # 题目描述

In a deck of cards, each card has an integer written on it.

Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

Each group has exactly X cards. All the cards in each group have the same integer.

Example 1:

``````Input: [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
``````

Example 2:

``````Input: [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
``````

Example 3:

``````Input: [1]
Output: false
Explanation: No possible partition.
``````

Example 4:

``````Input: [1,1]
Output: true
Explanation: Possible partition [1,1]
``````

Example 5:

``````Input: [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2]
``````

Note:

1. 1 <= deck.length <= 10000
2. 0 <= deck[i] < 10000

## # 解题方法

### # 遍历

``````[1,1,1,1,2,2,2,2,2,2]
``````

Python代码如下：

``````class Solution(object):
def hasGroupsSizeX(self, deck):
"""
:type deck: List[int]
:rtype: bool
"""
count = collections.Counter(deck)
X = min(count.values())
for x in range(2, X + 1):
if all(v % x == 0 for v in count.values()):
return True
return False
``````

### # 最大公约数

``````[1,1,2,2,2,2]
``````

C++代码如下：

``````class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> counter;
for (int d : deck) {
counter[d] ++;
}
int res = 0;
for (auto& c : counter) {
res = gcd(c.second, res);
}
return res > 1;
}
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
};
``````

## # 日期

2018 年 9 月 30 日 —— 9月最后一天啦！ 2018 年 11 月 24 日 —— 周日开始！一周就过去了～ 2020 年 3 月 27 日 —— 开始整合资源