781. 森林中的兔子
森林中有未知数量的兔子。提问其中若干只兔子 “还有多少只兔子与你(指被提问的兔子)颜色相同?” ,将答案收集到一个整数数组 answers 中,其中 answers[i] 是第 i 只兔子的回答。
给你数组 answers ,返回森林中兔子的最少数量。
示例 1:
输入:answers = [1,1,2]
输出:5
解释:
两只回答了 “1” 的兔子可能有相同的颜色,设为红色。
之后回答了 “2” 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 “2” 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5 只:3 只回答的和 2 只没有回答的。
示例 2:
输入:answers = [10,10,10]
输出:11
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rabbits-in-forest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
void quick(int *a,int low,int high){
if(low<high){
int l=low,h=high,p=a[low];
while(low<high){
while(low<high&&a[high]>=p){
high--;
}
a[low]=a[high];
while(low<high&&a[low]<=p){
low++;
}
a[high]=a[low];
}
a[low]=p;
quick(a,l,low-1);
quick(a,low+1,h);
}
}
int numRabbits(int* answers, int answersSize){
quick(answers,0,answersSize-1);
int i;
int val=answers[0];
int cnt=val;
int count=0;
for(i=1;i<answersSize;i++){
if(answers[i]==0){
count=count+1;
continue;
}
if(answers[i]==val&&cnt!=0){
cnt--;
continue;
}
if(cnt==0||answers[i]!=val){
count=val+1+count;
val=answers[i];
cnt=val;
}
}
count=val+1+count;
return count;
}