snow-swallow / blog

Seek more? Go to Issues :-)
1 stars 0 forks source link

914. 卡牌分组 - hasGroupsSizeX #75

Open snow-swallow opened 4 years ago

snow-swallow commented 4 years ago

题目

给定一副牌,每张牌上都写着一个整数。 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组: 每组都有 X 张牌。 组内所有的牌上都写着相同的整数。 仅当你可选的 X >= 2 时返回 true。

思路

  1. 用hashmap 统计每个数字的个数 counts
  2. 求counts 的最大公约数

考点: 最大公约数 gcd

代码

/**
 * @param {number[]} deck
 * @return {boolean}
 */
var hasGroupsSizeX = function(deck) {
    const gcd = (...arr) => { 
        const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); 
        return [...arr].reduce((a, b) => _gcd(a, b)); 
    };
    let counts = {};
    for (let i = 0; i < deck.length; i ++) {
        map[deck[i]] = (map[deck[i]] || 0) + 1;
    }
    const values = Object.values(counts);
    return gcd(...values) >= 2;
};

测试用例

Inputs: [0,0,0,1,1,1,2,2,2]
Expected output: true
---
Inputs: [1,1,2,2,2,2,2,2]
Expected output: true
---
Inputs: [1,1]
Expected output: true
---
Inputs: [1,1,1,2,2,2,3,3]
Expected output: false
---
Inputs: [1]
Expected output: false

https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/