# 781. 森林中的兔子

示例:



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  阅读(50)  评论(0编辑  收藏  举报