781. Rabbits in Forest
LeetCode 781. Rabbits in Forest
Description
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers
are placed in an array.
Return the minimum number of rabbits that could be in the forest.
Note:
answers
will have length at most1000
.Each
answers[i]
will be an integer in the range[0, 999]
.
Tags
Hash Table, Math
Solution
相同颜色的兔子看见其他同色兔子的数目一定相同,反之,若两只兔子看见与自身同色兔子数目不同则这两只一定不是同色。因此,我们使用哈希表,把报数相同的兔子划分为同一组,并将每一组可计算出的最少兔子数目累加到结果上。
例如有13只兔子回答5,并假设其中1只兔子为红色,还有1只为蓝色,则说明森林里至少有红色兔子和蓝色兔子各6只。为最小化可能的兔子总数,我们假设这12只兔子都在这13只内。这时还有一只额外的兔子有着不同于红色和蓝色的颜色,则我们可以得到兔子的最少数目为18。
一般地,设有 只兔子回答 ,则至少有 种不同的颜色,且每种兔子有 只。因此兔子数目至少为 。
Rabbits that share the same color should answer the same number; conversely, if 2 rabbits answer differently, they must not be the same color. Thus, here we apply a hash table to partition rabbits with the same number of response into the same group, then calculate the minimun number of rabbits for each group and add the result to the final answer.
For example, there are 13 rabbits answer "5", and assuming that one of them is red and one is blue, we would mean that there are at least 6 red and 6 blue rabbits each in the forest. To minimize the total number of rabbits, we suppose that all 12 rabbits are within these 13, and there is an extra rabbit whose coler is neither red nor blue. Therefore, we can conclude that the minimum of rabbits in this forest is 18.
Generally, let rabbits answer , then there are at least colors and there are rabbits of each color. Thus, the minimum number of rabbits that could be in the forest.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?