题目地址:https://leetcode.com/problems/rabbits-in-forest/description/

题目描述

Ina 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.

Examples:

Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0

Note:

1、 answerswillhavelengthatmost1000.;
2、 Eachanswers[i]willbeanintegerintherange[0,999].;

题目大意

兔子会报出和自己颜色相同的兔子数量,求最少的兔子数。

解题方法

充分理解大神的思路:

If x+1 rabbits have same color, then we get x+1 rabbits who all answer x. now n rabbits answer x. If n%(x+1)==0, we need n/(x+1) groups of x+1 rabbits. If n%(x+1)!=0, we need n/(x+1) + 1 groups of x+1 rabbits. the number of groups is math.ceil(n/(x+1)) and it equals to (n+i)/(i+1) , which is more elegant.

翻译一下:

当某个兔子回答x的时候,那么数组中最多允许x+1个兔子同时回答x,那么我们统计数组中所有回答x的兔子的数量n:

若n%(x+1)==0,说明我们此时只需要 n/(x+1) 组个数为x+1的兔子。

若n%(x+1)!=0,说明我们此时只需要 n/(x+1) + 1 组个数为x+1的兔子。

那么这两种情况可以通过 ceil(n/(x+1)) 来整合,而这个值也等于 (n + x) / (x + 1).

可以理解为,对每个数字进行记数,如果其出现的次数n能整除(x+1),说明能够成一个颜色,所以x+1个兔子。如果不能整除的话,说明有n/(x+1) + 1组兔子。然后一个简化计算的方案。

代码:

class Solution(object):
    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        count = collections.Counter(answers)
        print count
        return sum((count[x] + x) / (x + 1) * (x + 1) for x in count)

1 2 3 4 5 6 7 8 9

C++代码如下:

class Solution {
public:
    int numRabbits(vector<int>& answers) {
        int res = 0;
        unordered_map<int, int> m;
        for (int a : answers) m[a]++;
        for (auto a : m) {
            res += (a.second + a.first) / (a.first + 1) * (a.first + 1);
        }
        return res;
    }
};

1 2 3 4 5 6 7 8 9 10 11 12

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发