好久没刷题了,今天碰巧看见一道很有趣的题,给大家分享分享:
https://leetcode.com/problems/rabbits-in-forest/description/
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: 5 Explanation: 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. Input: answers = [10, 10, 10] Output: 11 Input: answers = [] Output: 0
题意: 树林中有一些兔子,其中一些兔子告诉你有多少只兔子与它的颜色相同,求树林中最少有多少兔子。
解法:刚看到题目的时候,是不是很蒙蔽呢,感觉类似于脑筋急转弯。
* 网上看到个超级秒的解法,也是看了半天才看懂 * 首先明白:对于每个兔子,回答颜色数量不同的属于不同的族群,回答颜色一样的属于一样的族群 * 那么可以使用hash table 来统计 * 思路是:贪心法:使用一个hash map 来保存 dict[k]表示具有相同颜色的K只兔子的群落,还能容纳多少只兔子 感觉解法其实也用到了数学原理
详见代码注释:
class Solution { public int numRabbits(int[] answers) { Map<Integer, Integer> count = new HashMap<>(); int res = 0; for (int i = 0; i < answers.length; i++) { count.put(answers[i] + 1, 0); } for (int i = 0; i < answers.length; i++) { int sameColorNum = answers[i] + 1; int leftRabbit = answers[i]; //如果相同颜色的K只兔子的群落还能容纳兔子,那就容纳下一只兔子,容量减一 if (count.get(sameColorNum) > 0) { count.put(sameColorNum, count.get(sameColorNum) - 1); } else { // 如果相同颜色的K只兔子的群落不能下容纳兔子,则将当前族群有的兔子数加到结果上去 res += sameColorNum; // 目前第i只兔子的回答是leftRabbit,说明与它颜色相同的兔子族群count[sameColorNum]还有leftRabbit只 // 则count[sameColorNum]的容量可以扩大到leftRabbit count.put(sameColorNum, leftRabbit); } } return res; } }
原文地址:https://www.cnblogs.com/shawshawwan/p/9374654.html
时间: 2024-10-14 12:17:38