LeetCode 781. Rabbits in Forest
考点 | 难度 |
---|---|
Greedy | Medium |
题目
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)