LeetCode-3.27-914-E-卡牌分组(X of a Kind in a Deck of Cards )

文章目录


给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。

In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
Each group has exactly X cards.
All the cards in each group have the same integer.

示例 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
解释:没有满足要求的分组。

思路

本题用到的是朴素的数学模拟,本质上是将所有元素出现的个数进行求最大公约数,最大公约数不为1即可恰好分成几个组。解题过程分为3个部分。
(1)统计所有出现的数的个数。整体遍历一遍,统计个数,存到普通数组hash中,但是此时的hash表是浪费空间的,很多位置是没有元素,表现出来value=0
(2)移动数组。为了方便后面的前后相邻位置一一比较,此处先将所有元素都移动到前面来,使之没有空位置。
(3)求最大公约数。整体便利一遍,求前后两个元素的最大公约数。

解法

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        
        int len = deck.length;
        if(len <= 1){
            return false;
        }

        //1.统计个数
        int[] hash = new int[len];
        for(int i = 0; i < len; i++){
            hash[deck[i]]++;
        }
        
        // 2.移动数组
        int j = 0;
        for(int i = 0; i < len; i++){
            if(hash[i] != 0){
                if(i != j){
                    hash[j] = hash[i];
                }
                j++;
            }
        }
        
        //3.求最大公约数
        for(int i = 0; i<j; i++){
            hash[i+1] = getCom(hash[i],hash[i+1]);
            if(hash[i+1] == 1){
                return false;
            }
        }
        
        return true;
    }
    
    private int getCom(int a, int b){
        int big = a > b ? a : b;
        int small = a > b ? b : a;
        
        if(small==0 || big % small == 0){
            return small;
        }
        return getCom(big % small, small);
    }
}
发布了194 篇原创文章 · 获赞 20 · 访问量 7968

猜你喜欢

转载自blog.csdn.net/Xjheroin/article/details/105144652