Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

914. X of a Kind in a Deck of Cards #88

Open
Tcdian opened this issue Mar 27, 2020 · 1 comment
Open

914. X of a Kind in a Deck of Cards #88

Tcdian opened this issue Mar 27, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 27, 2020

914. X of a Kind in a Deck of Cards

给定一副牌,每张牌上都写着一个整数。

此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:

每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true

Example 1

Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2

Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.

Example 3

Input: deck = [1]
Output: false
Explanation: No possible partition.

Example 4

Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].

Example 5

Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].

Note

  • 1 <= deck.length <= 10^4
  • 0 <= deck[i] < 10^4
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 27, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} deck
 * @return {boolean}
 */
var hasGroupsSizeX = function(deck) {
    const counts = new Array(10000).fill(0);
    
    for (let i = 0; i < deck.length; i++) {
        counts[deck[i]] += 1; 
    }
    
    let GCD = counts[deck[0]];
    
    for (let i = 0; i < deck.length; i++) {
        GCD = getGCD(GCD, counts[deck[i]]);
        if (GCD < 2) {
            return false;
        }
    }
    
    return true;
    
    function getGCD(a, b) {
        return a % b === 0 ? b : getGCD(b, a % b);
    }
};

@Tcdian Tcdian removed the LeetCode label Apr 23, 2020
@Tcdian Tcdian added the Array label May 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant