博客
关于我
781. 森林中的兔子 Java
阅读量:351 次
发布时间:2019-03-04

本文共 1429 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要根据兔子的回答来计算森林中兔子的最少数量。每个兔子都会给出它们看到的同颜色兔子的数量,我们需要利用这些信息来推断出森林中兔子的总数。

方法思路

  • 输入处理:首先检查输入数组是否为空,如果为空,直接返回0。
  • 排序数组:对输入数组进行排序,以便更好地处理相同数量的回答。
  • 统计回答次数:遍历排序后的数组,统计每个数量出现的次数。
  • 计算兔子数量:对于每个数量,根据其出现次数和数量的关系,计算对应颜色的兔子数量。
    • 如果出现次数等于数量+1,则该颜色的兔子数量就是数量+1。
    • 如果出现次数小于数量+1,则该颜色的兔子数量是数量+1。
    • 如果出现次数大于数量+1,则该颜色的兔子数量是出现次数。
  • 求和:将所有颜色的兔子数量相加,得到森林中兔子的最少数量。
  • 解决代码

    import java.util.*;public class Solution {    public static int numRabbits(int[] answers) {        if (answers.length == 0) return 0;        Arrays.sort(answers);        int count = 0;        Map
    map = new HashMap<>(); int loc = 0; for (int i = 1; i < answers.length; i++) { if (answers[i] != answers[i - 1]) { map.put(answers[i - 1], i - loc); loc = i; } } map.put(answers[answers.length - 1], answers.length - loc); for (Entry
    entry : map.entrySet()) { int key = entry.getKey(); int value = entry.getValue(); if (value == key + 1) { count += value; } else if (value < key + 1) { count += key + 1; } else { count += key + 1 + (value - (key + 1)); } } return count; }}

    代码解释

  • 输入处理:检查输入数组是否为空,直接返回0。
  • 排序数组:对输入数组进行排序。
  • 统计回答次数:使用哈希表统计每个数量出现的次数。
  • 计算兔子数量:遍历哈希表,根据出现次数和数量的关系,计算每个颜色的兔子数量。
  • 求和:将所有颜色的兔子数量相加,得到最终结果。
  • 通过这种方法,我们可以准确地计算出森林中兔子的最少数量,确保考虑了所有可能的情况。

    转载地址:http://ploe.baihongyu.com/

    你可能感兴趣的文章
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>