【3月打卡】Leetcode-914 卡牌分組

題目

囉嗦的第一版

使用map統計數字個數
mm代表出現最少次數,如果mm==1,return false;
否則考慮分組中個數從2~mm的可能性,整除代表可以分

class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        if(deck.size()<=1) return false;
        unordered_map<int,int> mp;
        int mm=deck.size();
        for(int i=0;i<deck.size();i++)
            mp[deck[i]]++;
        for(auto item:mp)
            mm=min(mm,item.second);
        if(mm==1) return false;
        bool flag=true;
        for(int i=2;i<=mm;i++)
        {
            flag=true;
            for(auto item:mp)
            {
                if(item.second%i!=0)
                    flag=false;
            }   
            if(flag)
                return true; 
        }
        return flag;
    }   
};

精簡版——所有數求最大公約數

c++內置函數 :頭文件#include<algorithm> 函數__gcd(a,b)

class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        if(deck.size()<=1) return false;
        unordered_map<int,int> mp;
        for(int i=0;i<deck.size();i++)
            mp[deck[i]]++;
        int x=mp[deck[0]];
        for(auto item:mp)
        {
         	if(item.second==1||x<2) return false;
            x=gcd(item.second,x);
        }
        return x>=2;
    }   
    int gcd(int a,int b){
        if(a>b)
            swap(a,b);
        while(b%a!=0)
        {
            int tmp=a;
            a=b%a;
            b=tmp;
        }
        return a;
    }
};

優化版

可以考慮使用素數篩來篩出素數,參考鏈接
依照原則:如果一個整數 x,存在一個素數 p 滿足 x%p == 0,那麼 x 必然不是素數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章