[LeetCode] 914. 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

卡牌分组。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

根据以上题意,你需要将一些卡牌分成一组或者多组,使得分组后每组有X张牌,每组牌上都写着相同的整数。如果能做到就return true,否则就return false。

注意每组牌上都写着相同的整数这个条件,其实是允许你将同样牌面的牌分到多个组里的。所以思路是先用hashmap统计一下不同牌面的牌各自有几张,如果有任何一种牌面的牌小于2张的话就直接return false。同时在统计的时候,记录一下最小的出现次数。再次遍历hashmap的values(),这时需要找的是在所有牌的出现次数中,是否存在一个大于1的公约数,如果存在这个公约数,则说明能满足题意。为什么要大于1是因为题目要求X要>= 2。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean hasGroupsSizeX(int[] deck) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         for (int num : deck) {
 5             map.put(num, map.getOrDefault(num, 0) + 1);
 6         }
 7         // corner case
 8         for (int key : map.keySet()) {
 9             int value = map.get(key);
10             if (value < 2) {
11                 return false;
12             }
13         }
14         
15         // normal case
16         // find the smallest element/key
17         int minKey = Integer.MAX_VALUE;
18         for (int key : map.keySet()) {
19             minKey = Math.min(minKey, key);
20         }
21         int minValue = map.get(minKey);
22         
23         int res = minValue;
24         for (int value : map.values()) {
25             res = gcd(res, value);
26         }
27         return res > 1;
28     }
29     
30     private int gcd(int a, int b) {
31         if (a % b == 0) {
32             return b;
33         }
34         return gcd(b, a % b);
35     }
36 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13749441.html