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

一、问题描述
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;
	}
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值