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;
}
}
三、測試結果
雖然比較簡單,但堅持下去還是會有收穫的。
加油親愛的女孩,相信你會愛上程式設計的!