这是我参与11月更文挑战的第20天,活动详情查看:2021最后一次更文挑战」
Exclusive Time of Functions 函数的独占时间
LeetCode原题传送门636. 函数的独占时间
今天我们来学习一个需要用到栈stack
来解决的问题。这个问题的关键就是利用了栈的LIFO的性质。
原题
有一个 单线程 CPU 正在运行一个含有 n 道函数的程序。每道函数都有一个位于 0 和 n-1 之间的唯一标识符。
函数调用 存储在一个 调用栈 上 :当一个函数调用开始时,它的标识符将会推入栈中。而当一个函数调用结束时,它的标识符将会从栈中弹出。标识符位于栈顶的函数是 当前正在执行的函数 。每当一个函数开始或者结束时,将会记录一条日志,包括函数标识符、是开始还是结束、以及相应的时间戳。
给你一个由日志组成的列表 logs ,其中 logs[i] 表示第 i 条日志消息,该消息是一个按 "{function_id}:{"start" | "end"}:{timestamp}" 进行格式化的字符串。例如,"0:start:3" 意味着标识符为 0 的函数调用在时间戳 3 的 起始开始执行 ;而 "1:end:2" 意味着标识符为 1 的函数调用在时间戳 2 的 末尾结束执行。注意,函数可以 调用多次,可能存在递归调用 。
函数的 独占时间 定义是在这个函数在程序所有函数调用中执行时间的总和,调用其他函数花费的时间不算该函数的独占时间。例如,如果一个函数被调用两次,一次调用执行 2 单位时间,另一次调用执行 1 单位时间,那么该函数的 独占时间 为 2 + 1 = 3 。
以数组形式返回每个函数的 独占时间 ,其中第 i 个下标对应的值表示标识符 i 的函数的独占时间。
On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.

Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.
Ecample 1:
Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3,4]
Explanation:
Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.
Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.
Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.
So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.
Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]
Output: [8]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls itself again.
Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.
Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.
So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.
Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]
Output: [7,1]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls function 1.
Function 1 starts at the beginning of time 6, executes 1 units of time, and ends at the end of time 6.
Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time.
So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:7","1:end:7","0:end:8"] Output: [8,1] Input: n = 1, logs = ["0:start:0","0:end:0"] Output: [1] 复制代码
提示:
- 1 <= n <= 100
- 1 <= logs.length <= 500
- 0 <= function_id < n
- 0 <= timestamp <= 109
- 两个开始事件不会在同一时间戳发生
- 两个结束事件不会在同一时间戳发生
- 每道函数都有一个对应 "start" 日志的 "end" 日志
思考线
解题思路
在第一次做这道题的时候,我觉得需要用到栈的性质来维护谁在执行。但是经过示例的分析后我觉得似乎不需要用栈来维护了,只需要确定好四种情况就行了。假设我们需要确定某个函数的执行时间,当前函数为n, 下一个调用函数为 n + 1,这四种情况分别是
- n is start, n + 1 is start => n用时:T(n+1) - T(n)
- n is start, n + 1 is end => n用时:T(n+1) - T(n) +1
- n is end, n+1 is start => n用时:T(n+1) - T(n) -1
- n is end, n+1 is end => n+1 用时:T(n+1) - T(n)
于是得到代码如下
/**
* @param {number} n
* @param {string[]} logs
* @return {number[]}
*/
var exclusiveTime = function(n, logs) {
const res = new Array(n).fill(0);
for(let i = 0; i < logs.length -1;i ++) {
const [id, state, time] = logs[i].split(':');
const [n_id, n_state, n_time] = logs[i+1].split(':');
if(state === n_state && n_state ==='start') {
res[id] += n_time - time;
} else if(state === 'start' && n_state === 'end') {
res[id] += n_time - time + 1;
} else if(state === 'end' && n_state === 'start') {
res[id] += n_time - time - 1;
} else{
res[n_id] += n_time - time;
}
}
return res;
};
复制代码
上面所有的示例都通过了,但是当我点击提交的时候,却总有测试不通过的案例。于是我一步一步分析。结果发现如果用上面的方法,我们在 state = start, n_state = end的时候,当存在多层嵌套的时候无法确定当时是那个函数在执行。举个例子 测试用例 ["0:start:0","1:start:2","1:end:5","2:start:7","2:end:7","0:end:8"]
,
当我们调用到"1:end:5","2:start:7"
时,time为6的这段时间其实是id=0的函数在执行,而我们却错误的当成是 id = 1 的函数在执行,所以说出错了。
看来我们还是要用栈来维护当前正在被调用的函数,来确定哪个函数正在被调用,当遇到 start
状态的函数,我们把它推入到栈中,当遇到end
状态的函数,我们把栈首的函数推出。
那么接下来我们要考虑的问题是如何确定当前函数的执行时间呢?还是假设现在有 id = n 和id= n+1的函数日志,则存在以下关系
- if n: start: time --> pre = time; if n: end : time --> pre = time + 1 ;
- if n +1: start: time ---> ExcTime = time - pre; if n+1: end:time ---> ExcTime = time -pre +1;
如此我们便可以得到正确的解法
/**
* @param {number} n
* @param {string[]} logs
* @return {number[]}
*/
var exclusiveTime = function(n, logs) {
const res = new Array(n).fill(0);
const stack = [0];
for (let i = 0; i < logs.length - 1; i++) {
const [id, state, time] = logs[i].split(':');
const [n_id, n_state, n_time] = logs[i + 1].split(':');
let pre;
if(state === 'start') {
pre = time - 0;
} else {
pre = time - 0 + 1;
}
if (n_state === 'start') {
res[stack[stack.length - 1]] += n_time - pre;
stack.push(n_id);
} else {
const run = stack.pop();
res[run] += n_time - pre + 1;
}
}
return res;
};
复制代码
经过优化我们可以先把logs[0]中的内容先提出来,然后从 i = 1,遍历,这样整个函数看起来就更美观。
var exclusiveTime = function(n, logs) {
const res = new Array(n).fill(0);
const first = logs[0].split(':');
const stack = [first[0]];
let pre = first[2];
for(let i = 1; i < logs.length; i++) {
const [id, state, time] = logs[i].split(':');
if(state ==='start') {
res[stack[stack.length-1]] += time - pre;
stack.push(id);
pre = time - 0;
} else {
const run = stack.pop();
res[run] += time -pre + 1;
pre = time - 0 + 1;
}
}
return res;
};
复制代码
关于本题的感想
- 要用对应问题的数据结构来解决问题会事半功倍。
- 在计算时间的节点上要想明白+1-1的问题。在本题中的体现是,start和end状态的计时问题。