| 考点 | 难度 |
|---|---|
| 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(Listemployees, int id) { Map map = new HashMap<> (); for (Employee e: employees){ map.put(e.id, e); } return dfs(id, map); } public int dfs(int id, Map m){ int ans = m.get(id).importance; for(int newId: m.get(id).subordinates){ ans += dfs(newId, m); } return ans; }



