ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

781. 森林中的兔子

2021-04-04 10:04:50  阅读:169  来源: 互联网

标签:map 781 int answers cnts 兔子 ans 森林


森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。

返回森林中兔子的最少数量。

示例:
输入: answers = [1, 1, 2]
输出: 5
解释:
两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 "2" 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。

输入: answers = [10, 10, 10]
输出: 11

输入: answers = []
输出: 0

说明:

  1. answers 的长度最大为1000
  2. answers[i] 是在 [0, 999] 范围内的整数。

 

 

a rabbit saying that there are x rabbits of the same color=>

there are x+1 rabbits in the same color=>

this x can be repeated x+1 times in an array=>

(1)Less than x+1 means that some rabbits are not talking;

(2)redundant means that there are rabbits of different colors,also has x+1.

=>

use the map to record the number of  x, then calculate (x+1) * ceil( map[x]/(x+1) ).

 

Java

class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer,Integer> map=new HashMap<>();
        int ans=0;
        for(int a:answers){
            map.put(a,map.getOrDefault(a,0)+1);
        }
        for(int n:map.keySet()){
            int cnts=map.get(n)/(n+1);
            ans+=map.get(n)%(n+1)==0?cnts*(n+1):(cnts+1)*(n+1);
        }
        return ans;
    }
}

python

class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        if not answers:return 0
        cnt=collections.Counter(answers)
        ans=0
        for n in cnt.keys():
            cnts=cnt[n]//(n+1)
            if cnt[n]%(n+1)==0:
                ans+=cnts*(n+1)
            else:
                ans+=(cnts+1)*(n+1)
        return ans

 

标签:map,781,int,answers,cnts,兔子,ans,森林
来源: https://www.cnblogs.com/xxxsans/p/14615619.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有