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

你可能感兴趣的文章
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>
mysql5.7安装
查看>>
mysql5.7性能调优my.ini
查看>>
MySQL5.7新增Performance Schema表
查看>>
Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
查看>>
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>