[Hash-Simple] 690. The importance of employees (queue + dfs two solutions)

[Title]
Given a data structure that saves employee information, it contains the employee's unique id, importance and the id of the immediate subordinates.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. Their corresponding importance is 15, 10, 5. Then the data structure of employee 1 is [1, 15, [2]], the data structure of employee 2 is [2, 10, [3]], and the data structure of employee 3 is [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, because it is not a direct subordinate, it is not reflected in the data structure of employee 1.
Now enter all employee information of a company and a single employee id to return the sum of the importance of this employee and all his subordinates.
[Example 1]
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1’s own importance It is 5, he has two direct subordinates 2 and 3, and the importance of 2 and 3 are both 3. Therefore, the total importance of employee 1 is 5 + 3 + 3 = 11.
[Note]
An employee can have at most one direct leader, but there can be multiple direct subordinates
. The number of employees does not exceed 2000.
[Code]
[Python]
Execution time:
164 ms, defeated 66.67% of users in all Python3 submissions
Memory consumption:
16 MB, defeated 48.89% of users in all Python3 submissions

"""
# Definition for Employee.
class Employee:
    def __init__(self, id: int, importance: int, subordinates: List[int]):
        self.id = id
        self.importance = importance
        self.subordinates = subordinates
"""
class Solution:
    def getImportance(self, employees: List['Employee'], id: int) -> int:
        findID=dict()
        for index,em in enumerate(employees):
            findID[em.id]=index
        idlist=[id]
        value=0
        while idlist:
            value+=employees[findID[idlist[0]]].importance
            idlist.extend(employees[findID[idlist[0]]].subordinates)
            idlist.pop(0)
        return value

[Method 2: dfs]

class Solution(object):
    def getImportance(self, employees, query_id):
        emap = {
    
    e.id: e for e in employees}
        def dfs(eid):
            employee = emap[eid]
            return (employee.importance +
                    sum(dfs(eid) for eid in employee.subordinates))
        return dfs(query_id)

Guess you like

Origin blog.csdn.net/kz_java/article/details/114488196