leetcode914-卡牌分组

原题

给定一副牌,每张牌上都写着一个整数。

此时,你需要选定一个数字 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. 1 <= deck.length <= 10000
  2. 0 <= deck[i] < 10000

解法

思想

哈希表获取所有数的出现次数,这些数字的最大公约数不小于2

代码

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i:deck){
            map.put(i,map.getOrDefault(i,0)+1);
        } 
        Integer count = null;
        for(Map.Entry<Integer,Integer> entry:map.entrySet()){
            if(count == null){
                if(entry.getValue()==1){
                    return false;
                }else{
                    count = entry.getValue();
                }
            }else{
                count = gcd(count,entry.getValue());
                if(count<2) return false;
            }
        }
        return true;
    }

    public int gcd(int a, int b) {
        return a % b == 0 ? b : gcd(b, a % b);
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode914-%e5%8d%a1%e7%89%8c%e5%88%86%e7%bb%84/

发表回复

登录后才能评论