leetcode每日一题 781. 森林中的兔子(数学&&hashmap) 2021/1/16 难度:中等

781. 森林中的兔子

题意:

给你一个answers数组,该数组存储每只兔子(知道有几个和它相同颜色的个数)。

从题目的数组推出,至少有几只兔子。

思路:

北大大佬的,
博主的表达太垃圾了,借鉴大佬的。

AC

class Solution {
    
    
public:
    int numRabbits(vector<int>& answers) {
    
    
        unordered_map<int,int> ma;
        for(auto x: answers)ma[x]++;
        int res = 0;
        for(auto x: ma){
    
    
            int col = x.first;
            int num = x.second;
            if(num%(col+1) == 0) res += num;
            else res += (num/(col+1)+1)*(col+1);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45377553/article/details/112755979