天天看点

10.力扣-树-员工的重要性

力扣-树-员工的重要性

员工的重要性(LeetCode 690)

  • 题目概述:给定一个保存员工信息的数据结构,它包含了员工 唯一的 id ,重要度 和 直系下属的 id 。比如,员工 1 是员工 2 的领导,员工 2 是员工 3 的领导。他们相应的重要度为 15 , 10 , 5 。那么员工 1 的数据结构是 [1, 15, [2]] ,员工 2的 数据结构是 [2, 10, [3]] ,员工 3 的数据结构是 [3, 5, []] 。注意虽然员工 3 也是员工 1 的一个下属,但是由于 并不是直系 下属,因此没有体现在员工 1 的数据结构中现在输入一个公司的所有员工信息,以及单个员工 id ,返回这个员工和他所有下属的重要度之和。
  • 题目案例:
    10.力扣-树-员工的重要性
  • 解题思路:员工管辖分布其实就是一个树结构,而重要性就相当于该结点的value,而获得value的方法就是将其子结点的value和自身自带value相加,所以这道题本身就是一个遍历问题。所以也就有两种解法:深度优先遍历和广度优先遍历

    (这里需要注意:题目所给员工是没有管辖顺序的,案例上是由顺序,其实它的案例库是有不按顺序的,所以不要想着依据给的员工顺序找遍历)

    解题关键:建立一个hashmap,键为员工编号,值为其对应的employee,这样可以通过它的员工编号(id),顺利找到他的importance和手下的子员工(我第一次做的时候值放的是importance,但是这样很麻烦的是员工有谁还需要传参数,不可取)

  • 深度优先java代码
//深度优先算法
class Solution1 {
    Map<Integer,Employee> hash=new HashMap<>();
    public int getImportance(List<Employee> employees, int id) {
        for(Employee employee:employees){
            hash.put(employee.id,employee);
        }
        return dfs(id);
    }
    public int dfs(int id){
        Employee employee=hash.get(id);
        int total=employee.importance;
        for(Integer num:employee.subordinates){
            total+=dfs(num);
        }
        return total;
    }
}

           
  • 广度优先java代码
class Solution2 {
    public int getImportance(List<Employee> employees, int id) {
        Map<Integer,Employee> hash=new HashMap<>();
        for(Employee employee:employees){
            hash.put(employee.id,employee);
        }
        int total=0;
        Queue<Integer> queue=new LinkedList<>();
        queue.add(id);
        while(!queue.isEmpty()){
            int tempId=queue.poll();
            Employee employee=hash.get(tempId);
            total+=employee.importance;
            for(Integer num:employee.subordinates){
                queue.add(num);
            }
        }
        return total;
    }
}