781.森林中的兔子

目标

森林中有未知数量的兔子。提问其中若干只兔子 "还有多少只兔子与你(指被提问的兔子)颜色相同?" ,将答案收集到一个整数数组 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

思路

对森林中的兔子提问 有多少只兔子与你颜色相同answers[i] 表示下标为 i 的兔子的回答,问森林中最少有多少只兔子。

假设被提问的兔子的颜色都不相同,那么兔子最少有 sum(answers[i]) + n,即被提问的兔子个数 n 加上与它们颜色相同的兔子个数。

如果被提问的兔子的颜色相同,那么它们的回答一定相同。可以根据回答进行分组,如果分组个数 groupCnt 超过了颜色个数 colorCnt,说明是其它颜色。只需要分组后对 groupCnt / colorCnt 向上取整,然后乘以 colorCnt 即可,即 ⌈groupCnt / colorCnt⌉ * colorCnt

代码


/**
 * @date 2025-04-20 14:09
 */
public class NumRabbits781 {

    public int numRabbits(int[] answers) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : answers) {
            map.merge(num, 1, Integer::sum);
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer colorCnt = entry.getKey() + 1;
            Integer groupCnt = entry.getValue();
            int colors = (groupCnt + colorCnt - 1) / colorCnt;
            res += colors * colorCnt;
        }
        return res;
    }
}

性能