Java/690.Employee Importance 员工的重要性
程序员文章站
2022-04-10 23:40:09
...
题目
代码部分(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;
}
}
}
}
-
将 id 对应的Employee 赋给 employee
-
创建队列并将第一个数据入队
-
若队列不为空,将其出队 poll() ,添加 importance 到 res 中
-
当第一层相关员工遍历完时,将其直系下属入队,第二层遍历完,再将第二层的直系下属,以此类推,直至结束
-
返回 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;
}
}
-
将 id 对应的 Employee 赋予 employee
-
获取其对应的下属 list
-
循环遍历下属,进行递归
-
返回 res