LeetCode 1376. Time Needed to Inform All Employees
Question
A company has n
employees with a unique ID for each employee from 0
to n - 1
. The head of the company has is the one with headID
.
Each employee has one direct manager given in the manager
array where manager[i]
is the direct manager of the i-th
employee, manager[headID] = -1
. Also it’s guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the employees of the company of an urgent piece of news. He will inform his direct subordinates and they will inform their subordinates and so on until all employees know about the urgent news.
The i-th
employee needs informTime[i]
minutes to inform all of his direct subordinates (i.e After informTime[i] minutes, all his direct subordinates can start spreading the news).
Return the number of minutes needed to inform all the employees about the urgent news.
Example
1 | Input: n = 1, headID = 0, manager = [-1], informTime = [0] |
Solution
这是一个典型Graph的题目,需要先构建关系,这样可以优化后面的过程。这个题需要找到最长的时间,进而可以通知所有的员工。所以,我们可以使用BFS的方法,进行每层搜索并且到达叶子节点(表明已经是最末端的员工了)的时候对比从开始到目前节点所耗用的时间。这个也有点类似于743. Network Delay Time,但是743每个一点可能有几条路选择。但是本题要求了每个人只能有一个manager,所以不会有多条路到达同一个点,只需要用BFS每层遍历即可。
Code
1 | // time: O(n) space:O(n) |