781. 森林中的兔子20201008

    科技2026-02-28  7

    森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。 返回森林中兔子的最少数量。

    链接:https://leetcode-cn.com/problems/rabbits-in-forest

    找规律,一定要写一写方便找到规律。 这里设n为兔子说的话,m为一共有几只兔子说了同样的话。在前面很平常了,需要统计元素出现次数用字典。

    count = {} for i in answers: if i not in count.keys(): count[i] = 1 else: count[i] += 1

    n=1时: n=2时: n=3时: 同理可以写下去,发现规律:

    符号为向下取整,比如5/2向下取整是2,2/5向下取整是0。 那么就可以直接写了

    class Solution: def numRabbits(self, answers: List[int]) -> int: if not answers: return 0 count = {} for i in answers: if i not in count.keys(): count[i] = 1 else: count[i] += 1 result = 0 for i in count.keys(): if i == 0: result += count[0] continue result = ((count[i]+i)//(i+1))*(i+1) + result return result
    Processed: 0.019, SQL: 9