1. 程式人生 > >781. Rabbits in Forest(python+cpp)

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

總結 :