当前位置: 代码迷 >> 综合 >> LeetCode-914.X of a Kind in a Deck of Cards(C++实现)
  详细解决方案

LeetCode-914.X of a Kind in a Deck of Cards(C++实现)

热度:34   发布时间:2023-12-16 19:30:20.0

一、问题描述
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
1)Each group has exactly X cards.
2)All the cards in each group have the same integer.

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

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

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

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

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

Note:
1)1 <= deck.length <= 10000
2)0 <= deck[i] < 10000
题目要求:
给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
(1)每组都有 X 张牌。
(2)组内所有的牌上都写着相同的整数。
(3)仅当你可选的 X >= 2 时返回 true。
二、思路及程序
思路:
遍历纸牌deck,统计deck中不同元素的个数及每个元素出现的次数,将不同元素出现的次数存放到容器N中,求N中最小的元素min,若min<2,则返回false;否则求min与N中每个元素的最小公约数b.对于每个元素,若b<=1,即最小公约数不存在,则返回false,否则返回true(即每个元素与min的最小公约数大于等于2时)。
程序:

bool hasGroupsSizeX(vector<int>& deck)
{int len = deck.size();set<int>number;vector<int>T;vector<int>N;for (int i = 0; i < len; i++){number.insert(deck[i]);}set<int>::iterator it;for (it=number.begin(); it!=number.end(); it++){for (int j = 0; j < len; j++){if(deck[j]==*it)T.push_back(deck[j]);}int n = T.size();N.push_back(n);T.clear();}vector<int>::iterator min = min_element(N.begin(), N.end());if (*min < 2)return false;else{for (int k = 0; k < N.size(); k++){int temp;int a = N[k];int b = *min;while (a%b != 0) {temp = a%b;a = b;b = temp;}if (b <= 1)   //b为N[k]和*min的最小公约数return false;}return true;}
}

三、测试结果
在这里插入图片描述
虽然比较简单,但坚持下去还是会有收获的。
加油亲爱的女孩,相信你会爱上编程的!