[914]. Grouping cards


link

Title Description

Here Insert Picture Description
Here Insert Picture Description

Greatest common divisor

1. Ideas

Each count of the number of the number that appears on mapthe.
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);
    }
}

3. Run Results:

Here Insert Picture Description

Published 55 original articles · won praise 1 · views 860

Guess you like

Origin blog.csdn.net/weixin_42469108/article/details/105134955