914、卡牌分组

  1. 914、卡牌分组
    1. 示例 1:
    2. 示例 2:
    3. 示例 3:
    4. 示例 4:
    5. 示例 5:
  2. 题解

914、卡牌分组

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

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

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

 

示例 1:

输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]

示例 2:

输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。

示例 3:

输入:[1]
输出:false
解释:没有满足要求的分组。

示例 4:

输入:[1,1]
输出:true
解释:可行的分组是 [1,1]

示例 5:

输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]

提示:

  • 1 <= deck.length <= 10000
  • 0 <= deck[i] < 10000

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

题解

1、统计,计算最大公约数

class Solution {
    private int gcd(int a,int b){
        if (a%b == 0) {
            return b;
        } else {
            return gcd(b,a%b);
        }
    }
    public boolean hasGroupsSizeX(int[] deck) {
        if (deck.length <= 1) {
            return false;
        }
        if (deck.length == 2) {
            if (deck[0] == deck[1]) {
                return true;
            }
        }
        // 利用Map集合
        Map<Integer,Integer> map = new HashMap<>();
        for (int item : deck) {
            if (map.containsKey(item)) {
                map.put(item,map.get(item)+1);
            } else {
                map.put(item,1);
            }
        }
        Iterator<Map.Entry<Integer,Integer>> it = map.entrySet().iterator();
        int a = 0,b;
        if (it.hasNext()) {
            a = it.next().getValue();
        }
        while (it.hasNext()) {
            b = it.next().getValue();
            a = gcd(a,b);
            if (a <= 1) {
                return false;
            } 
        }
        return true;
    }
}
// 使用数组做hash表
class Solution {
    private int gcd(int a,int b){
        if (a%b == 0) {
            return b;
        } else {
            return gcd(b,a%b);
        }
    }
    public boolean hasGroupsSizeX(int[] deck) {
        if (deck.length <= 1) {
            return false;
        }
        if (deck.length == 2) {
            if (deck[0] == deck[1]) {
                return true;
            }
        }
        int[] map = new int[10000];
        for (int item : deck) {
            map[item]++;
        }
        int a = -1;
        for (int i = 0;i < 10000;i++) {
            if (map[i] > 0){
                if (a == -1) {
                    a = map[i];
                } else {
                    a = gcd(a,map[i]);
                }
                if (a <= 1) {
                    return false;
                }
            }
        }
        return true;
    }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:914、卡牌分组

Count:535

Author:攀登

Created At:2020-07-26, 00:19:44

Updated At:2024-06-15, 15:52:32

Url:http://jiafeimao-gjf.github.io/2020/07/26/914%E3%80%81%E5%8D%A1%E7%89%8C%E5%88%86%E7%BB%84/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation