LeetCode 题解工作台
卡牌分组
给定一副牌,每张牌上都写着一个整数。 此时,你需要选定一个数字 X ,使我们可以将整副牌按下述规则分成 1 组或更多组: 每组都有 X 张牌。 组内所有的牌上都写着相同的整数。 仅当你可选的 X >= 2 时返回 true 。 示例 1: 输入: deck = [1,2,3,4,4,3,2,1] 输…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们先用数组或哈希表 `cnt` 统计每个数字出现的次数,只有当 是所有数字出现次数的约数时,即 是所有 `cnt[i]` 的最大公约数的约数时,才能满足题意。 因此,我们求出所有数字出现次数的最大公约数 ,然后判断其是否大于等于 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
- 每组都有
X张牌。 - 组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。
示例 1:
输入:deck = [1,2,3,4,4,3,2,1] 输出:true 解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
示例 2:
输入:deck = [1,1,1,2,2,2,3,3] 输出:false 解释:没有满足要求的分组。
提示:
1 <= deck.length <= 1040 <= deck[i] < 104
解题思路
方法一:最大公约数
我们先用数组或哈希表 cnt 统计每个数字出现的次数,只有当 是所有数字出现次数的约数时,即 是所有 cnt[i] 的最大公约数的约数时,才能满足题意。
因此,我们求出所有数字出现次数的最大公约数 ,然后判断其是否大于等于 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 deck 的长度和数组 deck 中的最大值。
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
cnt = Counter(deck)
return reduce(gcd, cnt.values()) >= 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N \log^2 N) |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Check if the candidate understands how to utilize hash tables for counting elements efficiently.
- question_mark
Observe if they can correctly identify the need for computing the GCD to ensure divisibility.
- question_mark
Pay attention to how the candidate approaches the verification of group divisibility and their understanding of the problem constraints.
常见陷阱
外企场景- error
Misunderstanding the need for GCD: Candidates might incorrectly assume that the card counts should simply be equal without considering GCD as a condition for partitioning.
- error
Failure to handle edge cases: Candidates should be cautious of scenarios where some cards have very few occurrences or all cards are identical.
- error
Inefficient frequency counting: If a candidate does not choose an efficient way to count card frequencies, such as using a hash table or dictionary, the solution could become too slow for larger inputs.
进阶变体
外企场景- arrow_right_alt
Consider variations where the deck contains a very large number of cards, requiring an optimized approach for counting and GCD computation.
- arrow_right_alt
What if some card values are missing or are spread out very unevenly? Discuss how the algorithm scales under these conditions.
- arrow_right_alt
Consider a constraint where the deck has a restricted number of card types or unique values, which could lead to different optimization strategies.