题干
给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 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
想法
首先需要说明的是:
你需要选定一个数字 X
这个x是任选的,不一定是你卡牌上的数字,我最初因为这个错误
如果暴力循环,就先记录每个数出现的次数,然后从X=2开始遍历,X必须是数组长度的公约数,X也必须是每个数字对应出现次数的公约数。
这里不再赘述代码
另一种相当于,
求每个数出现次数的最大公约数,
如果最大公约数大于等于2即可
Java代码
package daily;
public class HasGroupsSizeX {
public boolean hasGroupsSizeX(int[] deck) {
// 计数
int[] counter = new int[10000];
for (int num : deck) {
counter[num]++;
}
// 迭代求多个数的最大公约数
int x = 0;
for (int cnt : counter) {
if (cnt > 0) {
x = gcd(x, cnt);
if (x == 1) { // 如果某步中gcd是1,直接返回false
return false;
}
}
}
return x >= 2;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
HasGroupsSizeX hasGroupsSizeX = new HasGroupsSizeX();
int[] test = {1, 2, 3, 4, 4, 3, 2, 1};
int[] test1 = {1, 1, 1, 2, 2, 2, 3, 3};
int[] test2 = {1};
int[] test3 = {1, 1};
int[] test4 = {1, 1, 2, 2, 2, 2};
int[] test5 = {0, 0, 0, 0, 0, 1, 1, 2, 3, 4};
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test));
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test1));
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test2));
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test3));
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test4));
System.out.println(hasGroupsSizeX.hasGroupsSizeX(test5));
}
}
总结
数值小的时候,使用 int[10000]要快于hashmap
另外辗转相除法最近用的有点多,需要注意