• 力扣练习——67 森林中的兔子


    67 森林中的兔子

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

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

    示例:

    输入: answers = [1, 1, 2]

    输出: 5

    解释:

    两只回答了 “1” 的兔子可能有相同的颜色,设为红色。

    之后回答了 “2” 的兔子不会是红色,否则他们的回答会相互矛盾。

    设回答了 “2” 的兔子为蓝色。

    此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。

    因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。

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

    输出: 11

    输入: answers = []

    输出: 0

    2.输入说明
    首先输入answers数组的长度n,n<=1000

    然后输入n个整数,以空格分隔,每个整数在 [0, 999] 范围内
    3.输出说明
    输出一个整数
    4.范例
    输入
    3
    1 1 2
    输出
    5
    5.代码

    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include 
    
    using namespace std;
    
    int NumOfRabbits(vector<int> answers)
    {
    
    	
    	//    x/y  向上取整的写法  :(x+(y-1))/y    或者直接用ceil(x/y);
    	//    x/(y+1)    向上取整  :(x+y)/(y+1)
    	//参考贪心算法题解: https://leetcode.cn/problems/rabbits-in-forest/solution/sen-lin-zhong-de-tu-zi-by-leetcode-solut-kvla/
    	if (answers.size() == 0)
    		return 0;
    	int n = answers.size();
    	unordered_map<int, int>map;
    	for (auto t : answers)
    	{
    		map[t]++;//统计每个t出现的次数
    	}
    	int ans = 0;
    	for (auto s : map)
    	{
    		//同一颜色的兔子回答的数值必然是一样的
    		//但回答同样数值的,不一定就是同颜色兔子
    
    		int val = s.first;//回答相同颜色的兔子只数  ,若回答val,则至少有(val+1)只兔子是同种颜色的
    		int cnt = s.second;
    		if (cnt % (val + 1) == 0)
    			ans += (cnt / (val + 1))*(val + 1);//cnt/(val+1)计算出最少有几种颜色    每种颜色至少有val+1只兔子
    		else
    			ans+= (cnt / (val + 1)+1)*(val + 1);
    	}
    	return ans;
    }
    
    
    
    int main()
    
    {
    	int n,tmp;
    	cin >> n;
    	vector<int>answers;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> tmp;
    		answers.push_back(tmp);
    	}
    	int res = NumOfRabbits(answers);
    	cout << res << endl;
    	return 0;
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
  • 相关阅读:
    经典算法之冒泡排序
    中国凸轮滑块单元行业发展态势与投资趋势预测报告2022-2028年
    WAVE音频格式及及转换代码
    Android 眼睛 显示隐藏密码(ImageView)
    语音控制系统的安全挑战与防御策略(上)
    软考高级信息系统项目管理师系列论文九:论信息系统项目的采购管理
    HTML5+CSS3+JS小实例:霁青+翠蓝的Tabbar动画特效
    计算机竞赛 基于深度学习的植物识别算法 - cnn opencv python
    有名管道-
    【C++】unordered_map与unorder_set的封装(哈希桶)
  • 原文地址:https://blog.csdn.net/qq_43403657/article/details/126316030