问题描述:
给定一个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), 最多每个员工被访问一次*