【Leetcode】690. 员工的重要性

QUESTION

easy

题目描述

给定一个保存员工信息的数据结构,它包含了员工唯一的id重要度直系下属的id

比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。

现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。

说明

  • 一个员工最多有一个直系领导,但是可以有多个直系下属
  • 员工数量不超过 2000

SOLUTION

这道题的关键就在会不会产生死循环/重复计算的问题,比如但是此题中

  • 下属的下属不可能是上司
  • 两个上司肯定不会有同一个直系下属

所以实际上这就是一棵树,直接莽就完事了

方法一

class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        sort(employees.begin(), employees.end(), cmp);
        int res = 0;
        helper(employees, id, res);
        return res;
    }
private:
    static bool cmp(Employee* const &a, Employee* const &b){
        return a->id < b->id;
    }
    void helper(vector<Employee*> &employees, int id, int &res){
        int index = binarySearch(employees, id);
        res += employees[index]->importance;
        for(auto sub : employees[index]->subordinates){
            helper(employees, sub, res);
        }
    }
    int binarySearch(vector<Employee*> &employees, int id){
        int l = 0;
        int r = employees.size() - 1;
        while(l <= r){
            int mid = l + (r - l) / 2;
            if(employees[mid]->id < id) l = mid + 1;
            else if(employees[mid]->id > id) r = mid - 1;
            else return mid;
        }
        return -1;
    }
};

方法二

与方法一不同,查找 id 的方法是通过直接建立 id 与员工信息的映射,然后整体方法和一类似。

class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        unordered_map<int, Employee*> m;
        for (auto e : employees) m[e->id] = e;
        return helper(id, m);
    }
    int helper(int id, unordered_map<int, Employee*>& m) {
        int res = m[id]->importance;
        for (int num : m[id]->subordinates) {
            res += helper(num, m);
        }
        return res;
    }
};

当然也可以不用递归,用一个队列搞定

class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        int res = 0;
        queue<int> q{{id}};
        unordered_map<int, Employee*> m;
        for (auto e : employees) m[e->id] = e;
        while (!q.empty()) {
            auto t = q.front();
            q.pop();
            res += m[t]->importance;
            for (int num : m[t]->subordinates) {
                q.push(num);
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值