LeetCode 914. Card Packet C ++ description
Difficulty simply
given a deck of cards, each card are written on an integer.
At this point, you need to select a digital X, so that we can be full decks of cards according to the following rules into one or more groups:
Each group has X cards.
Within the group are written the same integer on all the cards.
> = 2 returns true only if you optional X.
Example 1:
Input: [1,2,3,4,4,3,2,1]
Output: true
interpretation: grouping is possible [1,1], [2,2], [3,3], [4,4 ]
Example 2:
Input: [1,1,1,2,2,2,3,3]
Output: false
interpretation: the packet does not satisfy the requirements.
Example 3:
Input: [1]
Output: false
interpretation: the packet does not satisfy the requirements.
Example 4:
Input: [1,1]
Output: true
interpretation: grouping is possible [1,1]
Example 5:
Input: [1,1,2,2,2,2]
Output: true
interpretation: grouping is possible [1,1], [2,2], [2,2]
prompt:
1 <= deck.length <= 10000
0 <= deck[i] < 10000
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
sort(deck.begin(),deck.end());
for(int i = 2; i <= deck.size(); i++){
//如果不能整除,则直接下一个
if(deck.size() % i != 0)
continue;
bool flag = true;
for(int j = 0; j < deck.size()/i; j++){
for(int k = j * i; k < (j+1) * i && k < deck.size(); k++){
if(deck[k] != deck[j*i]){
//如果不和第一个数一样,则退出
flag = false;
break;
}
if(!flag)
break;
}
}
if(flag)
return true;
}
return false;
}
};