博客
关于我
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 Workbench 数据库建模详解:从设计到实践
查看>>
MySQL Workbench 数据建模全解析:从基础到实践
查看>>
mysql workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>
mysql [Err] 1436 - Thread stack overrun: 129464 bytes used of a 286720 byte stack, and 160000 bytes
查看>>
MySQL _ MySQL常用操作
查看>>
MySQL – 导出数据成csv
查看>>
MySQL —— 在CentOS9下安装MySQL
查看>>
MySQL —— 视图
查看>>
mysql 不区分大小写
查看>>
mysql 两列互转
查看>>
MySQL 中开启二进制日志(Binlog)
查看>>
MySQL 中文问题
查看>>
MySQL 中日志的面试题总结
查看>>
mysql 中的all,5分钟了解MySQL5.7中union all用法的黑科技
查看>>
MySQL 中的外键检查设置:SET FOREIGN_KEY_CHECKS = 1
查看>>
Mysql 中的日期时间字符串查询
查看>>
mysql 中索引的问题
查看>>
MySQL 中锁的面试题总结
查看>>