781. Rabbits in Forest(python+cpp)

题目:

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;    
    }
};

总结 :

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值