likes
comments
collection
share

【LeetCode】636. 函数的独占时间

作者站长头像
站长
· 阅读数 20

【LeetCode】636. 函数的独占时间

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

    【LeetCode】636. 函数的独占时间

  • 题目示例

    【LeetCode】636. 函数的独占时间

  • 题目解析

    • 1 <= n <= 100
    • 1 <= logs.length <= 500
    • 0 <= function_id < n
    • 0 <= timestamp <= 109
    • 两个开始事件不会在同一时间戳发生
    • 两个结束事件不会在同一时间戳发生
    • 每道函数都有一个对应 "start" 日志的 "end" 日志

二、思路分析:

我们读取题目内容,要求模拟CPU运行函数从开始到结束的占用CPU时间,那么函数是怎么运行的,我们继续对题目进行审题,了解函数运行的规则:

  • 函数运行时,会进入到调用栈中存储
  • 函数调用过程会携带两种标识符,位于栈顶部的一定是当前在运行的函数
  • 函数中日志log包含函数序号、运行标识符、时间
  • 同一个时间只运行一个函数,同一时间只有一个函数结束运行

以上信息明确清楚后,我们对本题解答可以使用栈的方式对函数调用过程进行模拟即可,以下是解答思路:

  • 函数运行标识符只有start和end两种装,当是start状态时,则会进入到调用栈
  • 因此定义一个functmp来存储函数start状态信息函数编号和时间戳[idex,timestamp]
  • 因为位于functmp栈顶部的一定是正在执行的函数,因此当日志标识符还是start状态时,则直接使用新timestamp减去之前的timestamp保存在ans列表中
  • 当函数日志中出现end时,则将functmp顶部的信息弹出,则更新ans[idex]的时间,计算公式为timestamp-e+1
  • 当functmp列表不为空时,则函数运行并未结束,则functmp顶部的日志timestamp+1更新
class Solution(object):
    def exclusiveTime(self, n, logs):
        """
        :type n: int
        :type logs: List[str]
        :rtype: List[int]
        """
        ans = [0]*n
        functmp = []
        while logs:
            log = logs.pop(0)
            idex,tmp,timestamp = log.split(":")
            idex,timestamp = int(idex),int(timestamp)
            if "s" in tmp:
                if functmp:
                    ans[functmp[-1][0]] += timestamp - functmp[-1][1]
                    functmp[-1][1] = timestamp
                functmp.append([idex,timestamp])
            else:
                i,e = functmp.pop()
                ans[i] += timestamp - e + 1
                if functmp:
                    functmp[-1][1] = timestamp + 1        
        return ans

三、总结:

【LeetCode】636. 函数的独占时间

  • 时间复杂度:O(n),n为logs的数量
  • 空间复杂度:O(n),n为logs的数量

以上是本期内容,欢迎大佬们点赞评论,下期见~~~