题目描述
给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度 和 直系下属的id。
比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。
现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。
示例 1:
输入: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
输出: 11
解释:
员工1自身的重要度是5,他有两个直系下属2和3,而且2和3的重要度均为3。因此员工1的总重要度是 5 + 3 + 3 = 11。
注意:
一个员工最多有一个直系领导,但是可以有多个直系下属
员工数量不超过2000。
思路:subordinates数组存放的包括自己的重要性,复杂度不谈了,很高,今天的刷题异常困难,可能是把昨天的好运都用掉了吧
/*
// 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) {
int max = 0;
for (Employee employee : employees) {
if(employee.id > max){
max = employee.id;
}
}
int []subordinate = new int[max + 1];
int result = 0;
//思路:首先将所有的下属放在subordinate数组中
//找到id
Queue<Employee> ids = new LinkedList<>();
for (Employee employee : employees) {
if(employee.id == id){
ids.offer(employee);
subordinate[id] = employee.importance;
break;
}
}
while (!ids.isEmpty()) {
Employee tem = ids.poll();
List<Integer> zhixi = tem.subordinates;
// System.out.println("下属为:"+zhixi);
for (Integer integer : zhixi) {
for (Employee employee : employees) {
if(employee.id == integer){
ids.offer(employee);
subordinate[integer] = employee.importance;
break;
}
}
}
}
for (int i = 0; i < subordinate.length; i++) {
result += subordinate[i];
}
return result;
}
}
换个思路:首先将其放入到hashmap中,然后将其进行直接找,效率大概提高一倍
代码
//换个思路:
int result = 0;
int max = 0;
for (Employee employee : employees) {
if(employee.id > max){
max = employee.id;
}
}
int []subordinate = new int[max + 1];
//首先放入到hashmap,这样方便取
Map<Integer, Employee> hash = new HashMap<>();
for (Employee employee : employees) {
hash.put(employee.id, employee);
}
Queue<Employee> ids = new LinkedList<>();
ids.offer(hash.get(id));
while (!ids.isEmpty()) {
Employee tEmployee = ids.poll();
subordinate[tEmployee.id] = tEmployee.importance;
List<Integer> list = tEmployee.subordinates;
for (Integer integer : list) {
ids.offer(hash.get(integer));
}
}
for (int i = 0; i < subordinate.length; i++) {
result += subordinate[i];
}
return result;
排名靠前的代码
class Solution {
Map<Integer, Employee> emap;
public int getImportance(List<Employee> employees, int queryid) {
emap = new HashMap();
for (Employee e: employees) emap.put(e.id, e);
return dfs(queryid);
}
public int dfs(int eid) {
Employee employee = emap.get(eid);
int ans = employee.importance;
for (Integer subid: employee.subordinates)
ans += dfs(subid);
return ans;
}
}