LeetCode 690. Employee Importance

本文介绍了一种高效算法,用于计算指定员工及其所有直接和间接下属的重要性总和。通过使用哈希表来存储员工信息,该算法仅需遍历一次员工列表即可完成计算。

题意:给一个员工的数据结构,保存了1.id 2.重要值 3.直接管辖的员工id。要求给出一个id,返回他和他的所有直接/间接下属的重要值之和。

solution:hash。用排序+暴力+递归的方法应该也是很好做的,但是效率肯定会受影响。使用hash只需要至多遍历一遍数组即可。

/*
// Employee info
class Employee {
public:
    // It's the unique ID of each node.
    // unique id of this employee
    int id;
    // the importance value of this employee
    int importance;
    // the id of direct subordinates
    vector<int> subordinates;
};
*/
class Solution {
public:
    /*
    访问一个元素首先在hash表中查找,没有就从i开始查找,并且把经过的元素都加入hash表。
    找到队首节点,将其sub添加进q,累加res,队首出列,循环直到q为空,返回结果。
    */
    int getImportance(vector<Employee*> employees, int id) {
        unordered_map<int, int> hash; // id - index
        queue<int> q;
        int i = 0;
        int res = 0;
        q.push(id);
        
        while ( !q.empty() ) {
            int curr_id = q.front();
            if ( hash.find(curr_id) != hash.end()  ) {
                for ( auto sub : employees[hash[curr_id]]-> subordinates) {
                    q.push(sub);
                }
                res += employees[hash[curr_id]]-> importance;
            }
            else {
                for ( ; i < employees.size(); i++ ) {
                    hash[employees[i]->id] = i;
                    if ( employees[i]->id == curr_id ) {
                        for ( auto sub : employees[i]-> subordinates) {
                            q.push(sub);
                        }
                        res += employees[i]-> importance;
                    }
                }                
            }
            q.pop();
        }
        return res;
    }
};

submission:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值