最近写力扣的题,想把自己的思路记录下来:
问题描述
力扣690.员工的重要性
题目分析:
我采用的方法是使用map将员工的id和员工对应起来,当输入要查找的id时,找到其下属,再将其重要度相加,直至员工无下属为止。
代码实现:
/*
// Definition for Employee.
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
};
*/
class Solution {
Map<Integer,Employee> map=new HashMap<Integer,Employee>();
public int getImportance(List<Employee> employees, int id) {
for(Employee e:employees){
map.put(e.id,e);
}
return sum(id);
}
public int sum(int id){
Employee e=map.get(id);
int sum=e.importance;
List<Integer> subordinates=e.subordinates;
for(int sub:subordinates){
sum+=sum(sub);
}
return sum;
}
}