LeetCode 690. Employee Importance
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
You have a data structure of employee information, which includes the employee’s unique id, their importance value, and their direct subordinates’ id.
You are given an array of employees employees where:
employees[i].id
is the ID of the ith employee.
employees[i].importance
is the importance value of the ith employee.
employees[i].subordinates
is a list of the IDs of the subordinates of the ith employee.
Given an integer id
that represents the ID of an employee, return the total importance value of this employee and all their subordinates.
思路
把每个employee的信息存储在一个HashMap里。新建一个helper function(depth first search),从给定的id
开始,遍历该employee的所有subordinates,这里用到了recursion。有了helper function之后可以直接返回这个function的结果。
答案
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> map = new HashMap<> ();
for (Employee e: employees){
map.put(e.id, e);
}
return dfs(id, map);
}
public int dfs(int id, Map<Integer, Employee> m){
int ans = m.get(id).importance;
for(int newId: m.get(id).subordinates){
ans += dfs(newId, m);
}
return ans;
}