Description:
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:
Each group has exactly X cards.
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:
题意:给定一个数组deck,计算是否可以将此数组中的所有元素进行分组,使得每组的元素个数相同,同时每组中的所有元素都相同;
解法:可以考虑利用暴力求解,要求每组中元素的个数大于或等于2,则我们从两个元素开始一直到相同元素的最小数量,计算是否可以进行此分组,具体流程如下
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
if (deck.length <= 1) {
return false;
}
Map<Integer, Integer> times = new HashMap<>();
for (int d: deck) {
times.put(d, times.getOrDefault(d, 0) + 1);
}
int minTimes = Integer.MAX_VALUE;
for (int key: times.keySet()) {
minTimes = times.get(key) < minTimes ? times.get(key) : minTimes;
}
if (minTimes < 2) {
return false;
}
for (int x = 2; x <= minTimes; x++) {
boolean res = true;
for (int key: times.keySet()) {
if (times.get(key) % x != 0) {
res = false;
break;
}
}
if (res) {
return res;
}
}
return false;
}
}