LeetCode 914. 卡牌分组(C++、python)

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

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

  • 每组都有 X 张牌。
  • 组内所有的牌上都写着相同的整数。

仅当你可选的 X >= 2 时返回 true

示例 1:

输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]

示例 2:

输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。

示例 3:

输入:[1]
输出:false
解释:没有满足要求的分组。

示例 4:

输入:[1,1]
输出:true
解释:可行的分组是 [1,1]

示例 5:

输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]


提示:

1 <= deck.length <= 10000

0 <= deck[i] < 10000

C++

class Solution {
public:
    int gcd(int a, int b)
    {
        if(a<b)
        {
            swap(a,b);
        }
        if(0==a%b)
        {
            return b;
        }
        else
        {
            return gcd(b,a%b);
        }
    }
    
    bool hasGroupsSizeX(vector<int>& deck) 
    {
        map<int,int> tmp;
        for(auto it:deck)
        {
            tmp[it]++;
        }
        vector<int> vec;
        for(auto it:tmp)
        {
            vec.push_back(it.second);
        }
        if(1==vec.size())
        {
            if(vec[0]>1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            int mod=gcd(vec[0],vec[1]);
            if(1==mod)
            {
                return false;
            }
            else
            {
                for(int i=2;i<vec.size();i++)
                {
                    mod=gcd(mod,vec[i]);
                    if(1==mod)
                    {
                        return false;
                    }
                }
                return true;
            }
        }        
    }
};

python

class Solution:
    def gcd(self, a, b):
        if a<b:
            a,b=b,a
        if 0==a%b:
            return b
        else:
            return self.gcd(b,a%b)
    
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        tmp={}
        for it in deck:
            if it not in tmp:
                tmp[it]=1
            else:
                tmp[it]+=1
        vec=[]
        for key in tmp:
            vec.append(tmp[key])
        if 1==len(vec):
            if 1==vec[0]:
                return False
            else:
                return True
        else:
            mod=self.gcd(vec[0],vec[1])
            if 1==mod:
                return False
            else:
                for i in range(2,len(vec)):
                    mod=self.gcd(mod,vec[i])
                    if 1==mod:
                        return False
                return True
                        
            
        

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/89259462