zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    docker-5-容器数据卷
    docker-4-镜像
    docker-3-常用命令(下)
    docker-3-常用命令(中)
    docker-3-常用命令(上)
    docker-2-安装
    Python中Unicode字符串
    Python中整数和浮点数
    Python中什么是变量
    Python中数据类型
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12950915.html
Copyright © 2011-2022 走看看