914. 卡牌分组
给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 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
public boolean hasGroupsSizeX(int[] deck) {
int[] arr = new int[1000];
for (int i : deck) {
arr[i]++;
}
int count = 0;
for (int i : arr) {
//取计数数组里面大于0的数 0 % i = i
if (i > 0) {
count = gcd(count, i);
//如果最大公因数为1的话 证明不符合题意
if (count == 1)
return false;
}
}
return true;
}
//辗转相除法 你可以算一下7和5的最大公因数
//7/5 = 1..2 5/2 = 2..1 2/1 = 2..0
private int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}