LeetCode每日一题(二)

914.卡牌分组

题目:

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

此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:

每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的X >= 2时返回 true

思路:

设一共有N张牌,由每组都有X张牌可知X%N==0

设每个出现的数字的频数是count(i),则只需证明GCD(count(0),count(1),...,count(k),N) >= 2

代码如下:

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        int N = deck.length;
        if (N <= 1) return false;
        
        int[] count = new int[10000];
        for (int i : deck)
            count[i]++;
        
        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);
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2020-03-27 13:16  Aries99C  阅读(120)  评论(0)    收藏  举报