LeetCode 题解工作台

卡牌分组

给定一副牌,每张牌上都写着一个整数。 此时,你需要选定一个数字 X ,使我们可以将整副牌按下述规则分成 1 组或更多组: 每组都有 X 张牌。 组内所有的牌上都写着相同的整数。 仅当你可选的 X >= 2 时返回 true 。 示例 1: 输入: deck = [1,2,3,4,4,3,2,1] 输…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们先用数组或哈希表 `cnt` 统计每个数字出现的次数,只有当 是所有数字出现次数的约数时,即 是所有 `cnt[i]` 的最大公约数的约数时,才能满足题意。 因此,我们求出所有数字出现次数的最大公约数 ,然后判断其是否大于等于 即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

此时,你需要选定一个数字 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 <= 104
  • 0 <= deck[i] < 104
lightbulb

解题思路

方法一:最大公约数

我们先用数组或哈希表 cnt 统计每个数字出现的次数,只有当 XX 是所有数字出现次数的约数时,即 XX 是所有 cnt[i] 的最大公约数的约数时,才能满足题意。

因此,我们求出所有数字出现次数的最大公约数 gg,然后判断其是否大于等于 22 即可。

时间复杂度 O(n×logM)O(n \times \log M),空间复杂度 O(n+logM)O(n + \log M)。其中 nnMM 分别是数组 deck 的长度和数组 deck 中的最大值。

1
2
3
4
5
class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        cnt = Counter(deck)
        return reduce(gcd, cnt.values()) >= 2
speed

复杂度分析

指标
时间O(N \log^2 N)
空间O(N)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

卡牌分组题解:数组·哈希·扫描 | LeetCode #914 简单