[leetcode] 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

分析:这个题目有点像智力题,就是说森林中有一些兔子,他们会告诉你有除了自己还有多少个兔子颜色和自己不同,然后要求计算满足条件的最少的兔子。很容易想到求最少兔子,那肯定每个“说话”的兔子都只有1只时,总的兔子最少。接下来就是观察数组,发现数组中有0,也就是说这1个兔子说没有人和他颜色一样,那么它肯定时独一无二的,所以要累加求0的个数;然后观察再上例中,发现说3的兔子只有一个,所以这里肯定是3+1个兔子。然后在对其他的兔子进行观察,用group这个变量代表每个index能保存的兔子数量。代码如下:

 1 public int numRabbits(int[] answers) {
 2         Map<Integer, Integer> map = new HashMap<>();
 3         for ( int r : answers ) map.put(r,map.getOrDefault(r,0)+1);
 4         int sum = 0;
 5         for ( int index : map.keySet()){
 6             if ( index == 0 ) sum+=map.get(0);
 7             else {
 8                 if ( map.get(index) > 1 ){
 9                     int group = index + 1; //一个族群里面可以有inde+1个兔子
10                     if ( map.get(index) <= group ) sum += group;
11                     else {
12                         int d = map.get(index) % group == 0 ? 0:1; //判断能否整除
13                         sum += group * ( map.get(index) / group + d);
14                     }
15                 }
16                 else sum = sum + index + 1;
17             }
18         }
19         return sum;
20     }

这个题目代码并不难写,主要就是里面的思路理清楚就行了。也没能总结出一些普遍的方法。

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9263806.html