两种方法,第一种用的广度收索,第二种是哈希表
class Solution {
public int getImportance(List<Employee> employees, int id) {
Employee boss=new Employee();
int imp=0;
for(Employee e:employees)
{
if(e.id==id)
boss=e;
}
employees.remove(boss);
Stack<Employee>stack=new Stack<Employee>();
stack.push(boss);
while(!stack.isEmpty())
{
Employee p=stack.pop();
imp+=p.importance;
List<Integer>ids=p.subordinates;
List<Employee>li=new ArrayList<Employee>();
for(Employee e:employees)
{
if(ids.contains(e.id))
{
stack.push(e);
li.add(e);
}
}
employees.removeAll(li);
}
return imp;
}
}
public class Solution{
HashMap<Integer,Employee> map;
public int getImportance(List<Employee> employees,int id){
map = new HashMap<>();
for(Employee e:employees)map.put(e.id,e);
return helper(map.get(id));
}
public int helper(Employee em) {
int res = em.importance;
for (int sub : em.subordinates) {
res += helper(map.get(sub));
}
return res;
}
}