Leetcode 690: Employee Importance

问题描述:

给定一个List,每一个元素是一个employee,计算其importance和其属下的importance之和。

在这里插入图片描述

之前没有接触过太多BDF题目,所以没想到这是一道BFS。用哈希表将员工的id与其人对应,避免每次查找员工是都是O(n),因为题目中没说一号员工在list的第一个位置,诸如此类。

答案的代码如下:

class Solution {
    Map<Integer, Employee> emap;
    public int getImportance(List<Employee> employees, int queryid) {
        emap = new HashMap();
        for (Employee e: employees) emap.put(e.id, e);
        return dfs(queryid);
    }
    public int dfs(int eid) {
        Employee employee = emap.get(eid);
        int ans = employee.importance;
        for (Integer subid: employee.subordinates)
            ans += dfs(subid);
        return ans;
    }
}

我的代码:稍长但是对于我来说比较好理解:

/*
// 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(int i=0; i<employees.size(); i++){
            map.put(employees.get(i).id, employees.get(i));
        }
        int total_importance=0;
        Stack<Employee> stack = new Stack<>();
        stack.push(map.get(id));
        while(!stack.isEmpty()){
            Employee thisEmployee=stack.pop();
            total_importance+=thisEmployee.importance;
            List<Integer> hisSubordinates = thisEmployee.subordinates;
            for(int j=0; j<hisSubordinates.size(); j++){
                stack.push(map.get(hisSubordinates.get(j)));
            }
        }
        return total_importance;
    }
}

**时间复杂度: O(N), 最多每个员工被访问一次*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值