博客
关于我
leetcode 781. Rabbits in Forest 解题思路
阅读量:156 次
发布时间:2019-02-28

本文共 1660 字,大约阅读时间需要 5 分钟。

In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

Return the minimum number of rabbits that could be in the forest.

Examples:Input: answers = [1, 1, 2]Output: 5Explanation:The two rabbits that answered "1" could both be the same color, say red.The rabbit than answered "2" can't be red or the answers would be inconsistent.Say the rabbit that answered "2" was blue.Then there should be 2 other blue rabbits in the forest that didn't answer into the array.The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

想要知道森林里多少个兔子,首先要确定至少有多少个颜色的兔子。很简单看answer中有多少个不同的值就好了。[1,1,2] 有两个不同的值1,2那么就有两种不同的颜色。但是还有一种情况,比如[1,1,1,2],那么其中有两个1可以看作是一组,1这种颜色已经饱和了,那么剩下的那个1就是另一组了。

饱和的意思是这样,假设某个兔子组里面有x+1个兔子,那么所有兔子的回答都是x。兔子组和组之间的兔子可以看作是隔离的,他们相互不认识,兔子只认识自己组里面的兔子。那么[1,1,1,2]其实就是[[1,1],[1],[2]] 三组,其中[1,1]是全部展现出来的。[1]隐藏了一只,[2]隐藏了两只。

那么[4,5,6,6] 就至少有 [[4],[5],[6],[6]] (4+1)+(5+1)+(6+1)= 18只

[2,2,2,2,2,3,4,5,5] =>[[2,2,2],[2,2],[3],[4],[5,5]] => (2+1)+(2+1)+(3+1)+(4+1)+(5+1)=21只

编码:使用unordered_map存储每组兔子个数和兔子的答案。遇到不同组的兔子,兔子总数量累加大盘count,遇到相同的兔子,每组兔子数量递减,直到减为0. 下次遇到相同颜色的兔子就是不同组的了。

class Solution {public:    int numRabbits(vector
& answers) { int count = 0; unordered_map
rabbits_map; for(int ans:answers) { if(!rabbits_map.count(ans+1) || rabbits_map[ans+1] == 0){ count += ans + 1; rabbits_map[ans+1] = ans; }else{ rabbits_map[ans+1]--; } } return count; }};

 

转载地址:http://fzfc.baihongyu.com/

你可能感兴趣的文章
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
MySQL DBA 进阶知识详解
查看>>
Mura CMS processAsyncObject SQL注入漏洞复现(CVE-2024-32640)
查看>>
Mysql DBA 高级运维学习之路-DQL语句之select知识讲解
查看>>
mysql deadlock found when trying to get lock暴力解决
查看>>
MuseTalk如何生成高质量视频(使用技巧)
查看>>
mutiplemap 总结
查看>>
MySQL DELETE 表别名问题
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>