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     }

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

  • 相关阅读:
    料理phpMyAdmin2.6以上版本数据乱码结果
    mysql 中字符集的选择
    关于MySQL中的mysqldump饬令的运用
    一些Mysql的优化经验
    MYSQL数据库初学者操作指南1
    MySQL 5.0 新特性教程 存储历程:第三讲
    Windows下MySQL PHP5的设置配备部署与phpBB2论坛的架设
    MySQL 5.0新特征教程 存储历程:第一讲
    MySQL 5.0 新特征教程 存储过程:第二讲
    Linux Apache Mysql PHP典范设置装备摆设1
  • 原文地址:https://www.cnblogs.com/boris1221/p/9263806.html
Copyright © 2011-2022 走看看