LeetCode-X of a Kind in a Deck of Cards

Description:
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 <= deck.length <= 10000
  • 0 <= deck[i] < 10000

题意:给定一个数组deck,计算是否可以将此数组中的所有元素进行分组,使得每组的元素个数相同,同时每组中的所有元素都相同;

解法:可以考虑利用暴力求解,要求每组中元素的个数大于或等于2,则我们从两个元素开始一直到相同元素的最小数量,计算是否可以进行此分组,具体流程如下

  1. 构建散列表times<key:数组元素, value:在数组中出现的次数>
  2. 遍历散列表times中所有键,得到元素出现的最小次数minTimes
  3. for x in [2, minTimes]:
  4. 遍历散列表,计算所有元素出现次数能否被x整除;若可以,则返回ture,否则,继续x的下一个取值
  5. 若遍历完所有的x值后,都不存在可以被x整除的情况,则返回false;
Java
class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        if (deck.length <= 1) {
            return false;
        }
        Map<Integer, Integer> times = new HashMap<>();
        for (int d: deck) {
            times.put(d, times.getOrDefault(d, 0) + 1);
        }
        int minTimes = Integer.MAX_VALUE;
        for (int key: times.keySet()) {
            minTimes = times.get(key) < minTimes ? times.get(key) : minTimes;
        }
        if (minTimes < 2) {
            return false;
        }
        for (int x = 2; x <= minTimes; x++) {
            boolean res = true;
            for (int key: times.keySet()) {
                if (times.get(key) % x != 0) {
                    res = false;
                    break;
                }
            }
            if (res) {
                return res;
            }
        }
        
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值