781. 森林中的兔子
思路:
统计报不同数字
n
n
n的兔子的数量
i
i
i,然后返回
c
e
i
l
(
i
n
+
1
)
∗
(
n
+
1
)
ceil(\frac{i}{n+1})*(n+1)
ceil(n+1i)∗(n+1)。
原因是
- 报不同数字的兔子肯定有不同的颜色,因为每种颜色的兔子应该等于(自己报的数+1),两只同颜色的兔子报的数字应该是一样的。
- 每只报n的兔子,最多和另外n只兔子构成一种颜色,这种颜色的兔子总数为n+1。因此要满足报n的兔子的颜色,至少需要 c e i l ( i n + 1 ) ∗ ( n + 1 ) ceil(\frac{i}{n+1})*(n+1) ceil(n+1i)∗(n+1)只兔子。
class Solution {
public int numRabbits(int[] answers) {
if(answers.length==0)
return 0;
// 每种数字个数统计
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<answers.length;i++){
map.put(answers[i], map.getOrDefault(answers[i], 0) + 1);
}
int cnt = 0;
for(Integer key: map.keySet()){
cnt += Math.ceil((double)map.get(key)/(key+1))*(key+1);
}
return cnt;
}
}