[LeetCode] 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]`.

Java实现

``` 1 class Solution {
2     public int numRabbits(int[] answers) {
3         // corner case
5             return 0;
6         }
7
8         // normal case
9         int res = 0;
10         int max = 0;
12         for (int i = 0; i < answers.length; i++) {
13             res += answers[i] + 1;
14             max = answers[i] + 1;
16             int start = i;
17             while (i < answers.length && k == answers[i] && i - start < max) {
18                 i++;
19             }
20             i--;
21         }
22         return res;
23     }
24 }```

hashmap的做法其实也很类似，因为用了额外空间的缘故，我们不需要对input数组排序。如果当前兔子看到的是0，那么说明没有其他的兔子跟当前的兔子同色，就直接res++；如果当前这只兔子看到的数量不在hashmap中，则res += a + 1，说明起码有a + 1只兔子且应该是一个新的颜色；如果当前兔子看到的数量存在于hashmap中，我们就累加，比如我们看到一个10，也许当前这只兔子就是这11只兔子中间的一个；但是如果10被看到的次数大于11次了，那么说明肯定是一个别的颜色了，需要把10从hashmap中移除。

Java实现

``` 1 class Solution {
2     public int numRabbits(int[] answers) {
3         // corner case
5             return 0;
6         }
7
8         // normal case
9         HashMap<Integer, Integer> map = new HashMap<>();
10         int res = 0;
11         for (int a : answers) {
12             if (a == 0) {
13                 res += 1;
14                 continue;
15             }
16             if (!map.containsKey(a)) {
17                 map.put(a, 0);
18                 res += a + 1;
19             } else {
20                 map.put(a, map.getOrDefault(a, 0) + 1);
21                 if (map.get(a) == a) {
22                     map.remove(a);
23                 }
24             }
25         }
26         return res;
27     }
28 }```

LeetCode 题目总结

[LeetCode] 781. Rabbits in Forest

(0)
(0)