LeetCode--914. X of a Kind in a Deck of Cards

问题链接:https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/

能想到的就是求多个数的公约数(只会求两个数的),但我不会求呀,然后想的解法就比较暴力,就是先找到数字出现次数中的最小值min,然后从min到2开始搜索找到能够被所有出现次数记录整除的数字。代码如下:

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        
        HashMap<Integer,Integer> map=new HashMap<>();
        int min=Integer.MAX_VALUE;
        for(int i=0;i<deck.length;i++)
        {
            if(map.containsKey(deck[i]))
                map.put(deck[i],map.get(deck[i])+1);
            else
                map.put(deck[i],1);
        }

        int[] arr=new int[map.size()];
        int i=0;

        for(Integer k:map.keySet())
        {
            min=Math.min(min,map.get(k));
            arr[i++]=map.get(k);
        }

        i=min;
        for(;i>=2;i--)
        {
            int j=0;
            for(;j<arr.length;j++)
            {
                if(arr[j]%i!=0)
                    break;
            }
            if(j!=arr.length)
                continue;
            else
                return true;
        }

        return false;
    }
}

看了Solutions里的优秀解法,原来就是求得的最小公约数与下一个数再求最小公约数,代码如下:

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        int[] count = new int[10000];
        for (int c: deck)
            count[c]++;

        int g = -1;
        for (int i = 0; i < 10000; ++i)
            if (count[i] > 0) {
                if (g == -1)
                    g = count[i];
                else
                    g = gcd(g, count[i]);
            }

        return g >= 2;
    }

    public int gcd(int x, int y) {
        return x == 0 ? y : gcd(y%x, x);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值