LeetCode每日一题781. 森林中的兔子

分析

定义一个哈希表mp,记录每个数出现的个数,同时把每个数插入到集合中。
遍历集合s:

  1. 0:没有人与自己相同,直接加mp[0]
  2. 其他数x:每组大小为(x+1)。
    求出商 k = m p [ x ] x + 1 k=\frac{mp[x]}{x+1} k=x+1mp[x]和余数 r = m p [ x ] % ( x + 1 ) r=mp[x]\%(x+1) r=mp[x]%(x+1)
    若余数r=0,说明刚好有k组,加上KaTeX parse error: Undefined control sequence: \* at position 2: k\̲*̲(x+1)
    余数不为0,需要k+1组,加上KaTeX parse error: Undefined control sequence: \* at position 6: (k+1)\̲*̲(x+1)

样例

[0,0,1,1,1] 

LeetCode每日一题781. 森林中的兔子_第1张图片

[0,0,0,1,1] 

LeetCode每日一题781. 森林中的兔子_第2张图片

C++ 代码
class Solution {
public:
    unordered_map mp;  //开一个哈希表
    set s;
    int ans;
    int numRabbits(vector& answers) {
        int n=answers.size();
        if(n<1) return 0;
        for(int i=0;i

你可能感兴趣的:(c++,数据结构,哈希表)