我用Java刷 leetcode 690. 员工的重要性
Posted 深林无鹿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我用Java刷 leetcode 690. 员工的重要性相关的知识,希望对你有一定的参考价值。
我的垃圾AC(脑溢血级别bfs 因为忘记用哈希表):
/*
// 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) {
int res = 0;
Queue<Employee> queue = new LinkedList<>();
for (Employee e: employees) {
if (e.id == id) {
queue.offer(e);
}
}
while (queue.peek() != null) {
Employee e = queue.poll();
res += e.importance;
for (int val : e.subordinates) {
for (Employee emp : employees) {
if (emp.id == val) {
queue.offer(emp);
}
}
}
}
return res;
}
}
我的改进DFS:AC时间100%
/*
// Definition for Employee.
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
};
*/
class Solution {
private Map<Integer, Employee> hashMap = new HashMap<Integer, Employee>();
public int getImportance(List<Employee> employees, int id) {
for (Employee e : employees) {
hashMap.put(e.id, e);
}
return dfs(id);
}
public int dfs(int id) {
Employee e = hashMap.get(id);
int total = e.importance;
for (int tid : e.subordinates) {
total += dfs(tid);
}
return total;
}
}
以上是关于我用Java刷 leetcode 690. 员工的重要性的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode690. 员工的重要性(BFS || DFS)
[LeetCode]690. Employee Importance员工重要信息