781. 森林中的兔子

森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 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

 

posted @ 2021-04-04 09:27  XXXSANS  阅读(64)  评论(0编辑  收藏  举报