【Leetcode 每日一题】781. 森林中的兔子

问题背景

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

给你数组 a n s w e r s answers answers,返回森林中兔子的最少数量。

数据约束

  • 1 ≤ a n s w e r s . l e n g t h ≤ 1000 1 \le answers.length \le 1000 1≤answers.length≤1000
  • 0 ≤ a n s w e r s [ i ] < 1000 0 \le answers[i] < 1000 0≤answers[i]<1000

解题过程

找规律,考虑到要求数量最少,假设当前数组元素是 i t e m item item,它共有 n u m num num 个等值元素,那么答案会增加 ⌈ n u m i t e m + 1 ⌉ \lceil \frac{num}{item + 1} \rceil ⌈item+1num⌉。

建立数组元素与数量之间的哈希映射,再遍历计算结果即可。

具体实现

java 复制代码
class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int item : answers) {
            count.merge(item, 1, Integer::sum);
        }
        int res = 0;
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            int item = entry.getKey();
            int num = entry.getValue();
            res += (item + num) / (item + 1) * (item + 1);
        }
        return res;
    }
}
相关推荐
2301_8002561117 分钟前
地理空间数据库中的CPU 和 I/O 开销
数据库·算法·oracle
一个不知名程序员www1 小时前
算法学习入门---结构体和类(C++)
c++·算法
XFF不秃头3 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
王老师青少年编程3 小时前
csp信奥赛C++标准模板库STL案例应用3
c++·算法·stl·csp·信奥赛·lower_bound·标准模版库
有为少年4 小时前
Welford 算法 | 优雅地计算海量数据的均值与方差
人工智能·深度学习·神经网络·学习·算法·机器学习·均值算法
Ven%5 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
山楂树の5 小时前
爬楼梯(动态规划)
算法·动态规划
谈笑也风生5 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法
智算菩萨5 小时前
强化学习从单代理到多代理系统的理论与算法架构综述
人工智能·算法·强化学习