leetcode 781. Rabbits in Forest 解题思路

https://leetcode.com/problems/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.

想要知道森林里多少个兔子,首先要确定至少有多少个颜色的兔子。很简单看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<int>& answers) {
        int count = 0;
        unordered_map<int,int> 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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值