Rabbits in Forest

作者: gattonero | 来源:发表于2018-02-13 01:18 被阅读8次

Rabbits in Forest

问题

森林中每个兔子都有自己的颜色,如果某些兔子说出与自己有相同颜色的兔子数量(不包括自己),那么如何根据这些数量计算最少有多少只兔子

解决方案

  • 分析问题,如果每一个数量代表了一种颜色,那么只要判断这种数量至少有多少种颜色就可以了
  • 文章中给出的解法,是用数量作为数组下标,这里提供另一种基于有序数组的解法,空间复杂度会低一点
class Solution {
    public int numRabbits(int[] answers) {
        if(answers.length==0)return 0;
                
        java.util.Arrays.sort(answers);
        int pre=answers[0],cur = pre,sum=0;
        for(int i=1;i<=answers.length;i++){
            if(i==answers.length){
                sum+=pre+1;
            }else{
                if(answers[i]==pre){
                    if(--cur<0){
                        cur = answers[i];
                        sum+=pre+1;
                    }
                }else{
                    sum+=pre+1;
                    cur = answers[i];
                }
                
                pre = answers[i];
            }
        }
        return sum;
    }
}
  • 注意作者提供的解法中有这么一段
ans += Math.floorMod(-count[k], k+1) + count[k];

这里可以看做 count[k]基于k+1的上界(不是术语,方便理解而已,比如2基于5的上界是5,12基于5的上界是15,Math.ceil求的是一个数基于1的上界等等)

相关文章

  • Rabbits in Forest

    Rabbits in Forest 问题 森林中每个兔子都有自己的颜色,如果某些兔子说出与自己有相同颜色的兔子数量...

  • Leetcode【781、869】

    问题描述:【Math】781. Rabbits in Forest 解题思路: 森林中的兔子。每个兔子都有颜色,其...

  • LeetCode 781. Rabbits in Forest

    @(LeetCode) 问题描述 在一个森林里,每只兔子有着某种颜色。部分兔子(也可能是全部)会告诉你额外还有多少...

  • [Math_Medium] 781. Rabbits in Fo

    原题:781. Rabbits in Forest 题目大意: 森林里每只兔子报告说有多少只兔子和它的颜色一样,求...

  • Rabbits

    (From Internet) 1 When I mention rabbit here, what do you...

  • Five Rabbits

    Five rabbits were hiding in the woods one day 1-2-3-4-5 j...

  • Rabbits 1.0.0

    如果只是想查看Rabbits 1.0.0的变化以及新版本的使用方法,可以直接查看最后一节。 路由在移动开发中的作用...

  • 通过句子背单词46

    1,On the orbit, the rabbits habitually inherited the meri...

  • Rabbits - Android路由框架

    什么是Rabbits? Rabbits是用于Android项目的路由组件。具有统一管理路由、支持动态更新等方便的特...

  • 觉得绘本很小儿科? 其实你根本不懂绘本!

    “Once upon a time there were four little Rabbits, and the...

网友评论

    本文标题:Rabbits in Forest

    本文链接:https://www.haomeiwen.com/subject/sszdtftx.html