当前位置:网站首页>781. 森林中的兔子
781. 森林中的兔子
2022-08-10 01:34:00 【小卢要刷力扣题】
781. 森林中的兔子
森林中有未知数量的兔子。提问其中若干只兔子 “还有多少只兔子与你(指被提问的兔子)颜色相同?” ,将答案收集到一个整数数组 answers 中,其中 answers[i] 是第 i 只兔子的回答。
给你数组 answers ,返回森林中兔子的最少数量。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rabbits-in-forest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
给兔子分组
先排序,让相同的兔子在一起
这样就可以让相同的兔子分组,组内自我消化
排序好了,我们要怎么计算出相同的兔子的数量呢,
我们发现第一种颜色有 4 只兔子的回答为 1
那么在第一种颜色中可以分为 2 只兔子为一组
因为 1 代表这除了自己还有另外一只兔子颜色相同
因此 2 只兔子为一组,因此第一种颜色的兔子有 4 只
到了第 2 种颜色
2 代表着除了自己还有 2 只兔子颜色相同
因此需要分成 3 只兔子为一组
但第二种颜色的兔子在数组中只有 2 只,无法凑齐 3 只
证明还有兔子没被调查,需要在额外补一只兔子,
因此第二种颜色的兔子数量为 3
同理可得,第三种颜色的兔子有 8 只
第四种颜色的兔子有 5 只,因为数组中只有 3 只,需要另外补 2 只,
第五种颜色的兔子有 6 只
计算公式
变量 x 代表有多少只兔子颜色相同
c 代表当前颜色的兔子在数组中有多少只
如果当前数是 x,有 c 只,有几组?
我们以 7 个 3 为例子
3 代表除了自己有 3 只兔子颜色相同
因此 4 只兔子为一组
我们需要分出 2 组
因此为 7/4 向上取整
那么怎么向上取整
原本是 a/b
向上取整变为
(a+(b-1))/b
因此最后公式为((c+x)/(x+1))*(x+1),
🦘代码
class Solution {
public int numRabbits(int[] answers) {
int n=answers.length;
if(answers==null||n==0){
return 0;
}
Arrays.sort(answers);
int x=answers[0];
int c=1;
int ans=0;
for(int i=1;i<n;i++){
if(x!=answers[i]){
ans+=((c+x)/(x+1))*(x+1);
x=answers[i];
c=1;
}else{
c++;
}
}
return ans+((c+x)/(x+1))*(x+1);
}
}
边栏推荐
- 【wpf】自定义事件总结(Action, EventHandler)
- .Net interview experience summary
- [论文阅读] Diverse Image-to-Image Translation via Disentangled Representations
- C# rounding MidpointRounding.AwayFromZero
- 【每日一题】1413. 逐步求和得到正数的最小值
- OpenCV图像处理学习三,Mat对象构造函数与常用方法
- Under pressure, there must be cowards
- Chip Information|Semiconductor revenue growth expected to slow to 7%, Bluetooth chip demand still growing steadily
- hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
- Button countdown reminder
猜你喜欢
随机推荐
使用IDEA的PUSH常见问题
UI遍历的初步尝试
Sikuli's Automated Testing Technology Based on Pattern Recognition
Solve the problem of sed replacement text containing special characters such as "/" and "#"
Unity顶点动画
one of the variables needed for gradient computation has been modified by an inplace
Unity开发者必备的编辑器技巧
openpose脚部标注问题梳理
unity 报错 Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe‘ code“ in Pla
[LeetCode] Find the sum of the numbers from the root node to the leaf node
Research on Ethernet PHY Chip LAN8720A Chip
牛客刷题——剑指offer(第四期)
彩色袜子题
sqlmap dolog外带数据
【引用计数器及学习MRC的理由 Objective-C语言】
基于FTP协议实现文件上传与下载
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
[网鼎杯 2020 青龙组]AreUSerialz
[论文阅读] Multimodal Unsupervised Image-to-Image Translation
Teach you how to write performance test cases