914. X of a Kind in a Deck of Cards

问题:

给定一个数组,如过将其中每X个相同的数组成一个group,正好分完,其中X>=2,成立的话,返回true,否则返回false

Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.

Example 3:
Input: deck = [1]
Output: false
Explanation: No possible partition.

Example 4:
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].

Example 5:
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
 

Constraints:
1 <= deck.length <= 10^4
0 <= deck[i] < 10^4

  

解法:

用unordered_map记录不同数字的count。

求count的最大公约数,如果这个最大公约数>=2则满足条件,返回true。

 

⚠️注意:

C++中使用了库函数:求最大公约数 __gcd(a,b)

扩展:最小公倍数lcm

代码参考:

 1 class Solution {
 2 public:
 3     bool hasGroupsSizeX(vector<int>& deck) {
 4         unordered_map<int, int> cout;
 5         int X=0;
 6         for(int a:deck){
 7             cout[a]++;
 8         }
 9         for(auto item:cout){
10             X=__gcd(X, item.second);
11         }
12         return X>=2;
13     }
14 };

 

posted @ 2020-05-24 14:26  habibah_chang  阅读(141)  评论(0编辑  收藏  举报