# 781. 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

Output: 0
``````

Note:

1. `answers` will have length at most `1000`.
2. Each `answers[i]` will be an integer in the range `[0, 999]`.

``````class Solution {
public:
int res = 0;
unordered_map<int, int> m;
for (int ans : answers) {
if (!m.count(ans + 1) || m[ans + 1] == 0) {
res += ans + 1;
m[ans + 1] = ans;
} else {
--m[ans + 1];
}
}
return res;
}
};
``````

``````class Solution {
public:
int res = 0;
unordered_map<int, int> m;
for (int ans : answers) ++m[ans];
for (auto a : m) {
res += (a.second + a.first) / (a.first + 1) * (a.first + 1);
}
return res;
}
};
``````

``````class Solution {
public:
int res = 0;
vector<int> cnt(1000, 0);
for (int ans : answers) cnt[ans] = (cnt[ans] + 1) % (ans + 1);
for (int i = 0; i < 1000; ++i) {
if (cnt[i] != 0) res += i + 1 - cnt[i];
}
}
};
``````

https://leetcode.com/problems/rabbits-in-forest/solution/

https://leetcode.com/problems/rabbits-in-forest/discuss/123206/Java-4-Liner-No-HashMap

https://leetcode.com/problems/rabbits-in-forest/discuss/114719/My-easy-Java-HashMap-solution

https://leetcode.com/problems/rabbits-in-forest/discuss/114721/Easy-and-Concise-Solution-C++JavaPython

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation