Python学习日记(1)LeetCode 1376

LetCode 1376

https://leetcode.com/problems/time-needed-to-inform-all-employees/

问题是要找到通知到所有employee的时间,那么如果知道所有employee知道的时间,那么就是求max。如何算employee知道的时间呢,只要找到到他的manager一直到head的路径,这个可以通过遍历树。这颗树现在是通过反向指针来做的(从子节点指向了父节点),那么从子节点就可以找到根节点(head)得到这个叶子节点employee收到通知的时间。中间可以优化一下的就是如果有父节点已经被算出了这个时间,就不需要继续重复计算了。

代码如下:

from typing import List

class Solution:
    def __getCost(self, pos: int, manager: List[int], informTime:List[int], cost:List[int]) -> int:
        if manager[pos] == -1:
            return informTime[pos]
        
        if cost[pos] > 0:
            return cost[pos]

        cost[pos] = self.__getCost(manager[pos], manager, informTime, cost) + informTime[pos]
        
        return cost[pos]

    def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
        if n == 0:
            return 0
        
        cost = [0]*n
        for i in range(0,n):
            self.__getCost(i, manager, informTime, cost)

        return max(cost)

sln = Solution()
assert(sln.numOfMinutes(0,0, [-1], [0]) == 0)
assert(sln.numOfMinutes(6, 2, [2, 2, -1, 2, 2, 2], [0,0, 1, 0, 0, 0]) == 1)
assert(sln.numOfMinutes(7, 6, [1, 2, 3, 4, 5, 6, -1], [0, 6, 5, 4, 3, 2, 1]) == 21)
assert(sln.numOfMinutes(15, 0, [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]) == 3)

这里比较有趣的是,我第一次在leetcode上用python写。发现 List[int] 这个类型在书上没有提到过,运行的时候告诉我找不到这个类型。Google了之后才发现原来是在类库里面 https://docs.python.org/3/library/typing.html, 是一些type hint,帮助更好的理解代码。

发布了1 篇原创文章 · 获赞 0 · 访问量 6

猜你喜欢

转载自blog.csdn.net/frankguodongchen/article/details/104816472
今日推荐