[力扣]914. 卡牌分组

卡牌分组

Posted by JinFei on April 9, 2020

题目描述

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

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

每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。

Example1:

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

Example2:

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

Example3:

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

Example4:

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

Example5:

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

提示

  • 1 <= deck.length <= 10000
  • 0 <= deck[i] < 10000

解题思路

  • 暴搜
  • 我们从2-max进行判断
  • 看看能不能分成组
  • 满足可分组有两个条件
      1. size 能被 X 整除
      1. count出现的次数,也能被 X 整除
class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        int size = deck.size();
        unordered_map<int, int> mmap;
        for(auto& i : deck){
            mmap[i]++;
        }
        for(int X = 2; X <= 10000; ++X){
            if(size % X == 0){
                bool flag = 1;
                for(auto& i : mmap){
                    if(i.second % X != 0){
                        flag = 0;
                        break;
                    }
                }
                if(flag){
                    return true;
                }
            }

        }
        return false;
    }
};