森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。
返回森林中兔子的最少数量。
示例:
输入: answers = [1, 1, 2]
输出: 5
解释:
两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 "2" 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
输入: answers = [10, 10, 10]
输出: 11
输入: answers = []
输出: 0
哈希表+贪心法
nums[i]+1
是对应第\(i\)只兔子相同颜色的人数(假设兔子是诚实的)。key = nums[i], val = cont
。nums[i]
一样的兔子,尽可能归为同一种颜色。简单来说,如果有5只兔子同时说3,那么一定有两种不同的颜色。class Solution {
public:
int numRabbits(vector<int>& answers) {
int n = answers.size(), ret = 0;
if(!n)
return ret;
unordered_map<int,int> mymap;
for(auto num:answers){
mymap[num]++;
}
for(auto iter = mymap.begin(); iter != mymap.end(); ++iter){
int rabbits = iter -> first + 1;
int cont = iter->second;
while(cont > 0){
ret += rabbits;
cont -= rabbits;
}
}
return ret;
}
};
原文:https://www.cnblogs.com/alyosha/p/14651224.html