友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
|
|
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

公众号的微信号是: jikerizhi。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
690. 员工的重要性
你有一个保存员工信息的数据结构,它包含了员工唯一的 id,重要度和直系下属的 id。
给定一个员工数组 employees,其中:
-
employees[i].id是第i个员工的 ID。 -
employees[i].importance是第i个员工的重要度。 -
employees[i].subordinates是第i名员工的直接下属的 ID 列表。
给定一个整数 id 表示一个员工的 ID,返回这个员工和他所有下属的重要度的 总和。
示例 1:
输入:employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1 输出:11 解释: 员工 1 自身的重要度是 5 ,他有两个直系下属 2 和 3 ,而且 2 和 3 的重要度均为 3 。因此员工 1 的总重要度是 5 + 3 + 3 = 11 。
示例 2:
输入:employees = [[1,2,[5]],[5,-3,[]]], id = 5 输出:-3 解释:员工 5 的重要度为 -3 并且没有直接下属。 因此,员工 5 的总重要度为 -3。
提示:
-
1 <= employees.length <= 2000 -
1 <= employees[i].id <= 2000 -
所有的
employees[i].id互不相同。 -
-100 <= employees[i].importance <= 100 -
一名员工最多有一名直接领导,并可能有多名下属。
-
employees[i].subordinates中的 ID 都有效。
思路分析
哈希+深度优先搜索。先用 Map 建立起 id 到用户的映射关系,再深度优先搜索所有下属员工的优先级。
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2026-05-17 20:07:23
*/
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> idMap = new HashMap<>();
employees.forEach(e -> idMap.put(e.id, e));
Queue<Integer> queue = new LinkedList<>();
queue.offer(id);
int result = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Integer no = queue.poll();
Employee employee = idMap.get(no);
result += employee.importance;
employee.subordinates.forEach(queue::offer);
}
}
return result;
}

