加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode 781. Rabbits in Forest (森林中的兔子)

发布时间:2020-12-14 04:33:03 所属栏目:大数据 来源:网络整理
导读:题目标签:HashMap 题目给了我们一组数字,每一个数字代表着这只兔子说 有多少只一样颜色的兔子。 我们把每一个数字和它出现的次数都存入map。然后遍历map,来判断到底有多少个一样颜色的group,因为这里可能会出现一种情况:同一种颜色的兔子,可能有好几组

题目标签:HashMap

  题目给了我们一组数字,每一个数字代表着这只兔子说 有多少只一样颜色的兔子。

  我们把每一个数字和它出现的次数都存入map。然后遍历map,来判断到底有多少个一样颜色的group,因为这里可能会出现一种情况:同一种颜色的兔子,可能有好几组。

?  所以利用 value / groupSize 和 value % groupSize 来判断,到底有多少只兔子需要计算,具体看code。

?

Java Solution:

Runtime: 3 ms,faster than 86.90%?

Memory Usage: 37.8 MB,less than 17.65%

完成日期:03/28/2019

关键点:利用 value 和 groupSize 之间的关系,来判断准确的数量

class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer,Integer> map = new HashMap<>();
        int result = 0;
        
        for(int answer : answers)
        {
            if(answer == 0)
                result++;
            else
                map.put(answer,map.getOrDefault(answer,0) + 1);
        }
        
        int groupCount = 0;
        int leftover = 0;
        
        for(int key : map.keySet())
        {
            int value = map.get(key);
            int groupSize = key + 1;
            
            groupCount = value / groupSize;
            leftover = value % groupSize;
                
            if(leftover > 0) 
                groupCount++;
                
            result += groupCount * groupSize;
        }

        return result;
    }
}

参考资料:N/A

LeetCode 题目列表 -?LeetCode Questions List

题目来源:https://leetcode.com/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读