LeetCode 题解工作台

森林中的兔子

森林中有未知数量的兔子。提问其中若干只兔子 "还有多少只其它兔子与你(指被提问的兔子)颜色相同?" ,将答案收集到一个整数数组 answers 中,其中 answers[i] 是第 i 只兔子的回答。 给你数组 answers ,返回森林中兔子的最少数量。 示例 1: 输入: answers = […

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,回答相同的兔子,可能属于同一种颜色,而回答不同的兔子,不可能属于同一种颜色。 因此,我们用一个哈希表 记录每种回答出现的次数。对于每种回答 及其出现次数 ,我们按照每种颜色有 $x + 1$ 只兔子的原则,计算出兔子的最少数量,并将其加入答案。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

森林中有未知数量的兔子。提问其中若干只兔子 "还有多少只其它兔子与你(指被提问的兔子)颜色相同?" ,将答案收集到一个整数数组 answers 中,其中 answers[i] 是第 i 只兔子的回答。

给你数组 answers ,返回森林中兔子的最少数量。

 

示例 1:

输入:answers = [1,1,2]
输出:5
解释:
两只回答了 "1" 的兔子可能有相同的颜色,设为红色。 
之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 "2" 的兔子为蓝色。 
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。 
因此森林中兔子的最少数量是 5 只:3 只回答的和 2 只没有回答的。

示例 2:

输入:answers = [10,10,10]
输出:11

 

提示:

  • 1 <= answers.length <= 1000
  • 0 <= answers[i] < 1000
lightbulb

解题思路

方法一:贪心 + 哈希表

根据题目描述,回答相同的兔子,可能属于同一种颜色,而回答不同的兔子,不可能属于同一种颜色。

因此,我们用一个哈希表 cnt\textit{cnt} 记录每种回答出现的次数。对于每种回答 xx 及其出现次数 vv,我们按照每种颜色有 x+1x + 1 只兔子的原则,计算出兔子的最少数量,并将其加入答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 answers\textit{answers} 的长度。

1
2
3
4
5
6
7
8
9
class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        cnt = Counter(answers)
        ans = 0
        for x, v in cnt.items():
            group = x + 1
            ans += (v + group - 1) // group * group
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The interviewer expects you to notice that an answer x defines a group size of x + 1, not just x matching rabbits.

  • question_mark

    They want a greedy counting argument showing why partially filled groups still force the full group cost.

  • question_mark

    They are checking whether you reach for a hash map quickly instead of trying to simulate rabbit colors explicitly.

warning

常见陷阱

外企场景
  • error

    Adding the frequency count directly and forgetting the hidden rabbits needed to complete a color group.

  • error

    Treating every repeated answer as one shared group even when the count exceeds x + 1 and must spill into another group.

  • error

    Mixing up x with x + 1, which breaks both the grouping formula and the example [1,1,2].

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Ask for the maximum possible rabbits instead of the minimum, which removes the tight greedy packing used in Rabbits in Forest.

  • arrow_right_alt

    Stream the answers one by one and maintain the same grouped counting logic online with incremental frequencies.

  • arrow_right_alt

    Return the number of color groups as well as the minimum rabbit count, using the same ceil(c / (x + 1)) computation per answer.

help

常见问题

外企场景

森林中的兔子题解:数组·哈希·扫描 | LeetCode #781 中等