-
发表于 2024.08.26
-
挺简单的一个问题,首先使用一个哈希表记录员工的
id
和Employee
对象的映射关系,然后使用BFS
遍历员工的下属,累加重要性即可。C++的做法:
/* // Definition for Employee. class Employee { public: int id; int importance; vector<int> subordinates; }; */ class Solution { public: int getImportance(vector<Employee*> employees, int id) { unordered_map<int, Employee*> id_to_employee; for(auto employee : employees) { id_to_employee[employee->id] = employee; } queue<int> q; int ans = 0; q.push(id); while (!q.empty()) { int cur = q.front(); q.pop(); auto cur_employee = id_to_employee[cur]; ans += cur_employee->importance; for (auto &subordinate_id: cur_employee->subordinates) q.push(subordinate_id); } return ans; } };
- LC 题目链接
-