914. The card packet
link
Title Description
Greatest common divisor
1. Ideas
Each count of the number of the number that appears on map
the.
key
: Digital
value
: the number of occurrences in the
case of a packet success: the number of the greatest common divisor of all the numbers appear> = 2
2. Code
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
if(deck == null || deck.length == 0){
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{
int temp = map.get(deck[i]);
temp++;
map.put(deck[i],temp);
}
}
int temp = map.get(deck[0]);
for(Integer key : map.keySet()){
temp = gcd(map.get(key),temp);
}
if(temp >= 2){
return true;
}
return false;
}
//求两个数的最大公约数
//辗转相除法
private int gcd(int a ,int b){
return a % b == 0 ? b : gcd(b,a%b);
}
}