781. Rabbits in Forest**
https://leetcode.com/problems/rabbits-in-forest/
题目描述
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 most1000
. - Each
answers[i]
will be an integer in the range[0, 999]
.
C++ 实现 1
统计各个不同 answer 之间的个数, 然后我们来查找规律. 假设某兔子说 “跟自己颜色相同的兔子有 10 只”, 那么这里至少有 11 只兔子, 注意要把自身算上. 那么对于这 11 只兔子中的每一只兔子, 它都可以说 “跟自己颜色相同的兔子有 10 只”, 那么如果 answers
中 10 这个数字出现了 1 ~ 11
次, 不管是 1
次, 5
次还是 11
次, 反正只要个数在 11
以内(包括 11
), 那么使这个条件成立的兔子个数至少为 11
. 那如果 10 这个数字的个数超过了 11
次, 比方说出现了 20 次, 那么前 11 次可以认为是红色的 11 只兔子轮流说了一遍, 而后面的 9 次可以认为是蓝色的兔子轮流说了一遍: “跟自己颜色相同的兔子有 11 只”.
class Solution {
public:
int numRabbits(vector<int>& answers) {
unordered_map<int, int> record;
for (auto &c : answers) record[c] ++;
int res = 0;
for (auto &p : record) {
while (p.second > 0) {
res += p.first + 1;
p.second -= (p.first + 1);
}
}
return res;
}
};