当前位置: 首页 > 工具软件 > deck-of-cards > 使用案例 >

LeetCode-X of a Kind in a Deck of Cards

常乐
2023-12-01

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;
    }
}
 类似资料: