企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
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:** 1. `1 <= deck.length <= 10000` 2. `0 <= deck[i] < 10000` ``` var hasGroupsSizeX = function(deck) { // 最大公约数计算公式 function gcd(num1, num2) { // 利用辗转相除法来计算最大公约数 return num2 === 0 ? num1 : gcd(num2, num1 % num2); } // 相同牌出现次数Map let timeMap = new Map(); // 遍历牌 deck.forEach(num => { // 统计每张牌出现的次数 timeMap.set(num, timeMap.has(num) ? timeMap.get(num) + 1 : 1); }); // Map.protype.values()返回的是一个新的Iterator对象, 所以可以使用扩展运算符(...)来构造成数组 let timeAry = [...timeMap.values()]; /* 最大公约数 因为该数组是出现次数数组,最小值至少为1(至少出现1次), 所以默认赋值为数组首位对公约数计算无干扰 */ let g = timeAry[0]; // 遍历出现次数,计算最大公约数 timeAry.forEach(time => { // 因为需要比较所有牌出现次数的最大公约数,故需要一个中间值 g = gcd(g, time); }); // 判断是否满足题意 return g >= 2; }; ```