Java/690.Employee Importance 员工的重要性

90 篇文章 0 订阅
45 篇文章 0 订阅

题目


 

 

 

代码部分(25ms BFS)

class Solution {
    int res = 0;
    Employee employee;
    public int getImportance(List<Employee> employees, int id) {
        findId(employees, id);
        Queue<Employee> queue = new LinkedList();
        queue.add(employee);
        int size = queue.size();
        while(!queue.isEmpty()){
            Employee temp = queue.poll();
            res += temp.importance;
            for(int i : temp.subordinates){
                findId(employees, i);
                queue.add(employee);
            }
            size--;
            if(size == 0){                    // 上一层遍历后,将下一层队列长度赋予size
                size = queue.size();
            }
            
        }
        return res;
        
    }
    public void findId(List<Employee> employees, int id){
        for(Employee temp : employees){
            if(id == temp.id){
                employee = temp;
                break;
            }
        }
    }
}
  1. 将 id 对应的Employee 赋给 employee

  2. 创建队列并将第一个数据入队

  3. 若队列不为空,将其出队 poll() ,添加 importance 到 res 中

  4. 当第一层相关员工遍历完时,将其直系下属入队,第二层遍历完,再将第二层的直系下属,以此类推,直至结束

  5. 返回 res

 

代码部分二(24ms DFS)

class Solution {
    int res = 0;
    Employee employee;
    public int getImportance(List<Employee> employees, int id) {
        for(Employee temp : employees){
            if(temp.id == id){
                employee = temp;
                res += employee.importance;
                break;
            }
        }
        List<Integer> list = employee.subordinates;
        int len = list.size();
        for(int i : list){
            getImportance(employees, i);
        }
        return res;
        
    }
}
  1. 将 id 对应的 Employee 赋予 employee

  2. 获取其对应的下属 list

  3. 循环遍历下属,进行递归

  4. 返回 res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值