Wednesday, April 25, 2018

LeetCode 781 - Rabbits in Forest

https://leetcode.com/problems/rabbits-in-forest/description/
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]`.
https://leetcode.com/problems/rabbits-in-forest/discuss/114719/My-easy-Java-HashMap-solution
``````    public int numRabbits(int[] answers) {
int res = 0;
Map<Integer,Integer> map = new HashMap<>();
}
for(Integer n : map.keySet()){
int group = map.get(n)/(n+1);
res += map.get(n)%(n+1) != 0 ? (group+1)*(n+1) : group*(n+1);
}
return res;
}
``````
``` p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; min-height: 15.0px} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco} p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #931a68} p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #4e9072} span.s1 {color: #931a68} span.s2 {text-decoration: underline} span.s3 {color: #7e504f} span.s4 {color: #000000} span.s5 {color: #0326cc} span.s6 {text-decoration: underline ; color: #000000} span.Apple-tab-span {white-space:pre} public int numRabbits(int[] answers) { if (answers == null) return 0; Map<Integer, Long> counts = Arrays.stream(answers).boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); int count = 0; System.out.println(counts); for (Entry<Integer, Long> entry : counts.entrySet()) { count += (entry.getKey() + 1) * ceilDiv(entry.getValue(), entry.getKey() + 1); // (int) Math.ceil(entry.getValue() / ((entry.getKey() + 1))); } return count; } private long ceilDiv(long a, long b) { return a / b + ((a % b == 0) ? 0 : 1); } ```