One-pass solution.
During iterating through the input logs, there are 4 possible conditions:
- 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.
- 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. - 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.
- 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;
}
}

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

被折叠的 条评论
为什么被折叠?



