Tuesday, September 8, 2020

LeetCode [690] Employee Importance

 690. Employee Importance

Easy

You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates.

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.

 

Note:

  1. One employee has at most one direct leader and may have several subordinates.
  2. The maximum number of employees won't exceed 2000.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/

class Solution {
    Map<Integer, Employee> map;
    public int getImportance(List<Employee> employees, int id) {
        map = new HashMap<>();
        for(Employee e : employees){
            map.put(e.id, e);
        }
        return helper(id);
    }

    int helper(int id){
        int ret = map.get(id).importance;
        for(int s : map.get(id).subordinates){
            ret += helper(s);
        }
        return ret;
    }
}

写完code之后问了时间空间复杂度,follow-up问如果访问多次应该怎样改code,以及如果不是tree就是普通的graph题应该怎么解

但是一开始会问什么样的input data是valid的,讨论了半天,后来说必须是tree structure,然后问充要条件。我一直没想通为什么非得是tree(虽然lc上那题确实有这个条件,但感觉只是为了简单),我觉得只要是无圈图就行。。。然后follow up是如果要频繁调用的话,如何修改提高效率,就是加个记忆化,空间换时间,他说可以,不过改完就没时间了(45分钟,我也不知道为啥不能延长点),看地里说还有follow up是问如果是一般的图怎么做,我一脸问号,不知道有什么区别,按我理解只要有向无圈图总是有唯一子代树的,当时肥肠紧张以至于没敢和他argue,后来肥肠后悔,主要那老哥特别高冷,问什么就答一两个词那种,搞得人心态很差

No comments:

Post a Comment