【Leetcode_easy】914. X of a Kind in a Deck of Cards

problem

914. X of a Kind in a Deck of Cards

题意:每个数字对应的数目可以均分为多组含有K个相同数目该数字的数组。

思路:使用 map 结构记录数组中每个元素出现的次数,该题转化为求次数的最大公约数,若所有次数的最大公约数大于或者等于 2,返回 true,否则返回 false。

solution:

class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
    //Greatest Common Divisor(GCD)
        int tmp = 0;
        unordered_map<int, int> cnt;
        for(auto a:deck) cnt[a]++;
        for(auto a:cnt) tmp = __gcd(a.second, tmp);
        return tmp>1;
    }
    /*
    int gcd(int a, int b)
    {
        
    }*/
};

 

参考

1. Leetcode_easy_914. X of a Kind in a Deck of Cards;

2. discuss;

posted on 2019-07-26 19:23  鹅要长大  阅读(94)  评论(0编辑  收藏  举报

导航