LeetCode知识点总结 - 781

文章讲述了如何使用贪婪算法解决LeetCode中的问题781,即在森林中有未知数量的兔子,询问它们的颜色分布后,求最少可能的兔子数量。通过Counter计算不同颜色的兔子数量,然后利用答案数组计算组合,得出最少兔子总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 781. Rabbits in Forest

考点难度
GreedyMedium
题目

There is a forest with an unknown number of rabbits. We asked n rabbits “How many rabbits have the same color as you?” and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.

Given the array answers, return the minimum number of rabbits that could be in the forest.

思路

如果x+1只兔子有同一种颜色,最多有x+1只兔子回答x
如果n % (x + 1) == 0,一共有n / (x + 1)组x + 1
如果不为0,一共有n / (x + 1) + 1组x + 1

答案
class Solution(object):
    def numRabbits(self, answers):
        c = collections.Counter(answers)
        return sum((c[i] + i) / (i + 1) * (i + 1) for i in c)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值