算法思路:找两两计数值的最大公约数,如果这个最大公约数到最后依然 > 2,那么就成功了。
有两种代码写法,一种是HasMap计数,另一种因为给了数组的最大值,可以采用数组计数。
练习一下gcd算法:
public int gcd(int a ,int b){
return b == 0 ? a : gcd(b,a % b);
}
作者:pendygg
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/solution/zhe-bian-jian-yi-nin-shi-yong-int10000ni-by-pendyg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public boolean hasGroupsSizeX(int[] deck) {
if (deck == null || deck.length < 2){
return false;
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < deck.length; i++) {
if (!map.containsKey(deck[i])){
map.put(deck[i],1);
} else {
map.put(deck[i],map.get(deck[i]) + 1);
}
}
int GCD = map.get(deck[0]);
for (Map.Entry<Integer,Integer> entry : map.entrySet()){
GCD = (gcd(GCD,entry.getValue()));
if (GCD < 2){
return false;
}
}
return true;
}
public boolean hasGroupsSizeX1(int[] deck){
int[] count = new int[10000];
for (int i = 0; i < deck.length; i++) {
count[deck[i]]++;
}
int GCD = count[deck[0]];
for (int i = 0; i < 10000; i++) {
if (count[i] != 0){
GCD = gcd(GCD,count[i]);
if (GCD < 2){
return false;
}
}
}
return true;
}
作者:pendygg
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/solution/zhe-bian-jian-yi-nin-shi-yong-int10000ni-by-pendyg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。