zoukankan      html  css  js  c++  java
  • [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     }

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

  • 相关阅读:
    题目:写一个函数,求两个整数的之和,要求在函数体内不得使用+、-、×、÷。
    冒泡排序、插入排序、快速排序
    去掉字符串中重复的字符
    建立一个带附加头结点的单链表.实现测长/打印/删除结点/插入结点/逆置/查找中间节点/查找倒数第k个节点/判断是否有环
    day_1 练习2
    python-day 练习1
    python课程第一天笔记-la
    初学react,为什么页面不显示
    跟我一起学写插件开发
    网上下载的带特效的jquery插件怎么用
  • 原文地址:https://www.cnblogs.com/boris1221/p/9263806.html
Copyright © 2011-2022 走看看