LeetCode636. Exclusive Time of Functions

本文介绍了一种一过式日志解析算法,该算法能够有效地处理输入日志中的四种可能情况,并计算每个函数的独占运行时间。通过一次遍历实现高效处理,适用于跟踪系统中函数调用的时间分配。

One-pass solution.

During iterating through the input logs, there are 4 possible conditions:

  1. Previous log is “start”, current log is “start”. This means that either the previous function is calling some other function or it’s calling itself recursively. However, it makes no difference for those 2 cases, we just add the time gap between these 2 start to the total exclusive time of previous function.
  2. Previous log is “start”, current log is “end”. This means that current function runs to an end and haven’t call any other functions including itself. In this case we simply add this time gap to the total exclusive time of current function. Note this have a different calcuiating method, which is endTime - startTime + 1.
  3. Previous log is “end”, current log is “start”. This means that a previous function call is completed and the original function is running and is calling another function. Thus this time gap should be added to the original outer function that performs the call. However, there is another case for this as well. If there is no function performs the call, that means during this time gap the CPU is idle, and we should just ignore this time gap.
  4. Previous log is “end”, current log is “end”. This means that a previous function call is end, and the function that performs the call is completed as well. Thus this time gap should be added to the outer function that performs the call.

Summarize them up, we get the following solution.

This algorithm runs in O(n)time, O(n) space worst case for length-n input.

class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] ret = new int[n];
        Deque<Integer> deque = new ArrayDeque<>();
        String[] log = logs.get(0).split(":");
        deque.push(Integer.parseInt(log[0]));
        int prevTime = Integer.parseInt(log[2]);
        for (int i = 0; i < logs.size(); i++) {
            log = logs.get(i).split(":");
            int time = Integer.parseInt(log[2]);
            if (log[1].equals("start")) {
                if (!deque.isEmpty()) {
                    ret[deque.peek()] += (time - prevTime);
                }
                prevTime = time;
                deque.push(Integer.parseInt(log[0]));
            } else { // "end"
                ret[deque.pop()] += (time - prevTime + 1);
                prevTime = time + 1;
            }
        }

        return ret;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值