Given a data structure stored employee information, it contains a unique id employees, and the importance of immediate subordinates id.
For example, the staff is 1 staff leadership 2, 2 employees employee leadership 3. The importance of their respective 15, 10, 5. Then the structure of employee data is [1, 15, [2]], employee data structure 2 is [2, 10, [3]] data structure, the staff is 3 [3, 5, []]. Note that though a subordinate employee staff is 3 1, but since not immediate subordinates, and therefore not reflected in the data structure of employees 1.
Now enter a company all the employee information, and a single employee id, and returns the employees of the importance of his subordinates and all.
Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
employee 1 importance degree itself is 5, he there are two immediate subordinates 2 and 3, and the importance of 2 and 3 are 3. Thus the overall importance of the employee is 5 + 3 1 + 3 = 11.
note:
An employee has a direct leading up to, but can have more immediate subordinate
number of employees does not exceed 2,000.
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/employee-importance
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Analysis: 1, the importance of acquiring the target ID, but also the importance of acquiring a subsidiary, the most direct way is to traverse
Method 1: Using Recursive
public int getImportance(List<Employee> employees, int id) { if (employees == null || employees.size()==0) { return 0; } Map<Integer,Employee> map = new HashMap<>(); //将员工信息放入 map 因为map的查找复杂度O(1) for (Employee e:employees) { map.put(e.id,e); } return getImportance(id,map); } public int getImportance(int eid,Map<Integer,Employee> map) { Employee employee = map.get(eid); int result = employee.importance; for (Integer subId: employee.subordinates) { result += getImportance(subId,map); } return result; } 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; };