一、题目
给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度 和 直系下属的id。
比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。
现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employee-importance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
LeetCode题目链接
二、思路
计算该员工的重要度,需要不断的搜索下属列表,为了避免不断地搜索,我在这里选择了队列,通过不断将id所对应地下属列表元素进行入队,可以避免遗漏。
然后,对出出队地每个元素进行计算重要度。
三、代码
/*
// Employee info
class Employee {
// It's the unique id of each node;
// unique id of this employee
public int id;
// the importance value of this employee
public int importance;
// the id of direct subordinates
public List<Integer> subordinates;
};
*/
class Solution {
public int getImportance(List<Employee> employees, int id) {
// 队列中存放的是下属列表id
Queue<Integer> queue = new LinkedList<>();
// 先找到id(参数id)的重要度和直属下属
int result = 0; // 返回的结果
// 1.计算传进来的id的重要度,并且将下属列表中的重要度添加进队列中
for (int i = 0; i < employees.size(); i++) {
if (employees.get(i).id == id) {
result = employees.get(i).importance;
List<Integer> sub = employees.get(i).subordinates;
// 若下属列表中为空,不用进行队列添加操作,由于id唯一,因此,循环就不用进行遍历
if (sub == null){
break;
}
// 将初始id的下属列表添加到队列中
for (int j = 0; j < sub.size(); j++) {
queue.add(sub.get(j));
}
}
}
// 2.若没有下属,返回的是id自己的重要度
if (queue.isEmpty()){
return result;
}
// 3.取出队列中的元素id,计算重要度,同时将其下属列表添加到队列中
while(!queue.isEmpty()){
// (1)取队首元素
int curId = queue.poll();
// (2)找到该id的重要度
for (int i = 0; i < employees.size(); i++) {
if (employees.get(i).id == curId){
//(3) 进行重要度累加计算
result += employees.get(i).importance;
// (4)得到该id对应的下属列表
List<Integer> sub = employees.get(i).subordinates;
// (5)若下属列表中为空,不用进行队列添加操作,由于id唯一,因此,循环就不用进行遍历
if (sub == null){
break;
}
// (6)将该id的下属列表添加到队列中
for (int j = 0; j < sub.size(); j++) {
queue.add(sub.get(j));
}
}
}
}
return result;
}
}