博客
关于我
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/

你可能感兴趣的文章
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>
mysqlreport分析工具详解
查看>>
MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
查看>>
Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
查看>>
mysql_real_connect 参数注意
查看>>
mysql_secure_installation初始化数据库报Access denied
查看>>
MySQL_西安11月销售昨日未上架的产品_20161212
查看>>
Mysql——深入浅出InnoDB底层原理
查看>>
MySQL“被动”性能优化汇总
查看>>
MySQL、HBase 和 Elasticsearch:特点与区别详解
查看>>
MySQL、Redis高频面试题汇总
查看>>
MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
查看>>
mysql一个字段为空时使用另一个字段排序
查看>>
MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
查看>>
MYSQL一直显示正在启动
查看>>
MySQL一站到底!华为首发MySQL进阶宝典,基础+优化+源码+架构+实战五飞
查看>>