2021-04-04 781. 森林中的兔子 [HashMap]

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. 报不同数字的兔子肯定有不同的颜色,因为每种颜色的兔子应该等于(自己报的数+1),两只同颜色的兔子报的数字应该是一样的。
  2. 每只报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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值