[Leetcode] 781. Rabbits in Forest 解题报告

题目

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

Note:

  1. answers will have length at most 1000.
  2. Each answers[i] will be an integer in the range [0, 999].

思路

通过观察可知:同一种颜色的兔子的答案一定是相同的(但是答案相同的兔子不一定就是一种颜色),答案不同的兔子一定颜色不同。所以我们的思路就是首先把答案相同的兔子进行聚类。对于每组答案相同的兔子而言,如果它们都属于同一种颜色,那么参与回答的兔子数量一定不会超过它们的答案+1(例如,假如有3个兔子都回答说有另外1个兔子和它本身的颜色相同,那么这3个兔子不可能同样颜色,最好的可能是其中2个兔子颜色相同,而另外1个兔子是另外一种颜色,也有可能3个兔子的颜色各不相同)。根据这一限制,我们就知道回答这组答案的兔子的颜色数的最小可能,而每种颜色的兔子的个数即是它们的答案+1,这样就可以得到回答这组答案的兔子的最小可能颜色数。这样把所有组答案的兔子的最小可能个数加起来,就是题目所求。

实现中,我们用哈希表可以实现对每种答案的兔子的快速聚类,这样算法的时间复杂度和空间复杂度都为O(n)。

代码

class Solution {
public:
    int numRabbits(vector<int>& answers) {
        unordered_map<int, int> hash;
        for (auto answer : answers) {
            ++hash[answer];
        }
        int ret = 0;
        for (auto it = hash.begin(); it != hash.end(); ++it) {
            int group_num = ceil((double)it->second / (it->first + 1));
            ret += group_num * (it->first + 1);
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值