leetcode——第690题——员工重要性

题目
给定一个保存员工信息的数据结构,它包含了员工 唯一的 id ,重要度 和 直系下属的 id 。
现在输入一个公司的所有员工信息,以及单个员工 id ,返回这个员工和他所有下属的重要度之和。

/*
// Definition for Employee.
class Employee {
public:
    int id;
    int importance;
    vector<int> subordinates;
};
*/

class Solution {
public:
/***********************递归法************************/

// 递归法还不对
    unordered_map<int,Employee*> mp;

    void travel(Employee* node,int& result)
    {
        if(node == nullptr)
        {
            return;
        }
        result += node->importance;
        for(int i=0; i<node->subordinates[i]; i++)
        {
            // 错误::刚开始这里没有把 mp 定义为全局的
            travel(mp[node->subordinates[i]],result);
        }
        // 错误: 这儿没写返回值
        return;
    }

    int getImportance(vector<Employee*> employees, int id)
    {
        // 定义一个哈希表,用来存储员工的 id  以及这个员工对应的节点
        
        for(auto &it:employees)
        {
            mp[it->id] = it;
        }
        int result=0;
        travel(mp[id],result);
        return result;
    }

/************************迭代法********************************/
    // int getImportance(vector<Employee*> employees, int id) {
    //   // 这不就是相当于遍历树嘛  
    //   // 我选用层序遍历叭
    //   unordered_map<int,Employee*> mp;
    //   for(int i=0; i<employees.size(); i++)
    //   {
    //       mp[employees[i]->id] = employees[i];
    //   }
    //   queue<int> que;
    //   que.push(id);
    //   int result=0;
    //   while(!que.empty())
    //   {
    //       int size = que.size();
    //       int node = que.front();
    //       que.pop();
    //       result += mp[node]->importance;
    //       for(int i=0; i< mp[node]->subordinates.size(); i++)
    //       {
    //           que.push(mp[node]->subordinates[i]);
    //       }
    //   }
    //   return result;
    // }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值