781. Rabbits in Forest(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84329245

题目:

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.
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:
answers will have length at most 1000.
Each answers[i] will be an integer in the range [0, 999].

解释:
假设有x+1个兔子拥有同样的颜色red,那么会有x+1只兔子说出答案x,但是这x+1个兔子不一定都在数组answer中。
如果现在有n只兔子回答x
如果n%(x+1)==0,那么我们需要 n/(x+1)组 个数为x+1的兔子
如果n%(x+1)!=0,那么我们需要n/(x+1)+1组 个数为x+1的兔子
比如answer=[3,3,3,3,3],那么x=3,所以至少有两组 个数为4的兔子,也就是说,至少有2×4=8只兔子。
所以当务之急是先对answer统计一下,对于每个key算出对应的兔子数,累加即得到最终答案。
python代码:

from collections import Counter
from math import ceil
class Solution(object):
    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        _dict=Counter(answers)
        _sum=0
        for  key in _dict:
            _sum+=ceil(float(_dict[key])/(key+1))*(key+1)
        return int(_sum)

c++代码:

#include <map>
using namespace std;
class Solution {
public:
    int numRabbits(vector<int>& answers) {
        map<int,int>_count;
        for (auto x:answers)
            _count[x]++;
        int _sum=0;
        for(auto item: _count)
            _sum+=ceil((float)item.second/(item.first+1))*(item.first+1);
        return _sum;    
    }
};#include <map>
using namespace std;
class Solution {
public:
    int numRabbits(vector<int>& answers) {
        map<int,int>_count;
        for (auto x:answers)
            _count[x]++;
        int _sum=0;
        for(auto item: _count)
            _sum+=ceil((float)item.second/(item.first+1))*(item.first+1);
        return _sum;    
    }
};

总结 :

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84329245