Employee Importance
给一个Employee类, 里面有一个数组的子类的id和一个importance数字, 求他自己和他下面所有的id的importance的和
/*
// 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, List<Integer>> map = new HashMap<>();
Map<Integer, Integer> im = new HashMap<>();
Employee c = null;
for(Employee e : employees){
if(e.id == id)
c = e;
if(map.containsKey(e.id)){
map.get(e.id).addAll(e.subordinates);
}else{
map.put(e.id, e.subordinates);
}
im.put(e.id, im.getOrDefault(e.id, e.importance));
}
int res = 0;
res += sumUp(c.id, map, im);
return res;
}
private int sumUp(int id, Map<Integer, List<Integer>> map, Map<Integer, Integer> im) {
int sum = im.get(id);
for(int s : map.get(id)){
sum += sumUp(s, map,im);
}
return sum;
}
}