Question:
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:
Input: [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
Input: [1]
Output: false
Explanation: No possible partition.
Input: [1,1]
Output: true
Explanation: Possible partition [1,1]
Input: [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
Input: [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2]
Solution:
/**
* @param {number[]} deck
* @return {boolean}
*/
var hasGroupsSizeX = function(deck) {
// 先归类
let map = {};
for (let i=0; i<deck.length; i++) {
if (!map[deck[i]]) {
map[deck[i]] = 0
}
map[deck[i]]++;
}
// 找最小长度
let minLen;
for (let j in map) {
if (!minLen) {
minLen = map[j]
}else{
minLen = Math.min(minLen,map[j])
}
}
// 判断最小长度是否大于等于2
if (minLen<2) return false;
var getMgn = function (a,b) {
if (a % b === 0) {
return b
}
return arguments.callee(b, a % b);
}
for (let k in map) {
// 求公约数
let mgn = getMgn(map[k],minLen);
console.log(mgn,k,minLen,map[k])
if (mgn === 1) {
return false
}
}
return true
};
Runtime: 60 ms, faster than 100.00% of JavaScript online submissions for X of a Kind in a Deck of Cards.