当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.914.X of a Kind in a Deck of Cards 卡牌分组

LeetCode.914.X of a Kind in a Deck of Cards 卡牌分组

题目描述

914 X of a Kind in a Deck of Cards
https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/

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: 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].

Constraints:
1 <= deck.length <= 10^4
0 <= deck[i] < 10^4


解题过程

这道题思路梳理起来还有点儿费事,一开始以为是统计每个数出现的次数,如果全都相同就是true
后来发现不是,比如 6个1,9个2,则能分成x=3的小组
也就是说要先统计每个数出现的次数,然后计算所有次数的最大公约数gcd,如果gcd大于1则存在这样的x

求两个数的最大公约数的时间复杂度是 O(logn),所以
时间复杂度是 O(nlogc),n是数组元素个数,c是数组中最大的数
空间复杂度 O(n)

private static class SolutionV2020 {
    public boolean hasGroupsSizeX(int[] deck) {
        if (null == deck || deck.length < 2) {
            return false;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int n : deck) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        // 所有value的最大公约数
        int gcd = map.get(deck[0]);
        for (Integer n : map.values()) {
            gcd = gcd(n, gcd);
        }
        return gcd > 1;
    }

    // 循环求最大公约数
    private int gcd(int x, int y) {
        while (y != 0) {
            int remain = x % y;
            x = y;
            y = remain;
        }
        return x;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_914_CardsGroup.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_914_CardsGroup.java


上一篇 LeetCode.820.Short Encoding of Words 单词的压缩编码

下一篇 LevelDB

阅读
评论
461
阅读预计2分钟
创建日期 2020-03-27
修改日期 2020-03-27
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论