码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode781. Rabbits in Forest (Hash Table + Math)

时间:2018-07-26 23:46:24      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:不同   ict   nim   ash   mini   div   set   sub   therefore   

好久没刷题了,今天碰巧看见一道很有趣的题,给大家分享分享:

 

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;
    }
}

 

LeetCode781. Rabbits in Forest (Hash Table + Math)

标签:不同   ict   nim   ash   mini   div   set   sub   therefore   

原文地址:https://www.cnblogs.com/shawshawwan/p/9374654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!