690. Employee Importance - LeetCode
Question
Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
Solution
题目大意:
每个员工都有一个价值,求一个员工及其下属员工价值总和
思路:
构造一个map来映射每个员工id和员工详细信息,再构造一个队列来遍历员工数据
Java实现:
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> employeeMap = new HashMap<>();
for (Employee tmp : employees) {
employeeMap.put(tmp.id, tmp);
}
Queue<Employee> employeeQueue = new LinkedList<>();
employeeQueue.offer(employeeMap.get(id));
int importance = 0;
while (!employeeQueue.isEmpty()) {
Employee cur = employeeQueue.poll();
importance += cur.importance;
if (cur.subordinates == null) continue;
for (int tmp : cur.subordinates) {
employeeQueue.offer(employeeMap.get(tmp));
}
}
return importance;
}