1. 首页
  2. 软件开发
  3. day-40 员工的重要性

day-40 员工的重要性

  • 发布于 2024-09-26
  • 1 次阅读


思路
利用一个哈希表,把员工id作为key值,把员工信息(Employee)作为value值,再利用深度优先遍历即可

解题过程
把查询员工的重要度加入返回值,再dfs算法将下属员工的重要度加入返回值(如果下属员工还有下属员工,也利用dfs加入,以此类推)

Code

/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/

class Solution {

    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(map,id);
    }
    public int dfs(Map<Integer,Employee> map,int id){

        Employee e=map.get(id);
        int ans=e.importance;
        for(int i:e.subordinates){

            ans+=dfs(map,i);
        }
        return ans;
    }
}

原文链接: https://blog.csdn.net/qq_53568730/article/details/141557208