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,帮助更好的理解代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值