题目

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

题解

数字相同的,颜色一样,所以可以将n+1个回答为n的兔子认为颜色一样,打包计入。回答为n的兔子不足n+1时,这部分兔子就有n+1个。

code

  1. class Solution:
  2. def numRabbits(self, answers: List[int]) -> int:
  3. count = dict()
  4. for item in answers:
  5. if item in count:
  6. count[item]+=1
  7. else:
  8. count[item]=1
  9. # count = Counter(answers) python库还不很是熟悉,可以直接用这个
  10. ans = sum((x + y) // (y + 1) * (y + 1) for y, x in count.items())
  11. return ans