0636.函数的独占时间
描述
给出一个非抢占单线程CPU的 n 个函数运行日志,找到函数的独占时间。
每个函数都有一个唯一的 Id,从 0 到 n-1,函数可能会递归调用或者被其他函数调用。
日志是具有以下格式的字符串:function_id:start_or_end:timestamp
。例如:"0:start:0"
表示函数 0 从 0 时刻开始运行。"0:end:0"
表示函数 0 在 0 时刻结束。
函数的独占时间定义是在该方法中花费的时间,调用其他函数花费的时间不算该函数的独占时间。你需要根据函数的 Id 有序地返回每个函数的独占时间。
实例
输入:
n = 2
logs =
["0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"]
输出:[3, 4]
说明:
函数 0 在时刻 0 开始,在执行了 2个时间单位结束于时刻 1。
现在函数 0 调用函数 1,函数 1 在时刻 2 开始,执行 4 个时间单位后结束于时刻 5。
函数 0 再次在时刻 6 开始执行,并在时刻 6 结束运行,从而执行了 1 个时间单位。
所以函数 0 总共的执行了 2 +1 =3 个时间单位,函数 1 总共执行了 4 个时间单位。
说明
- 输入的日志会根据时间戳排序,而不是根据日志Id排序。
- 你的输出会根据函数Id排序,也就意味着你的输出数组中序号为 0 的元素相当于函数 0 的执行时间。
- 两个函数不会在同时开始或结束。
- 函数允许被递归调用,直到运行结束。
- 1 <= n <= 100
题解
使用stack
存储调用层级关系
关于每个log
,分成几种情况考虑
- 当前状态为
start
- 上一个状态为
start
- 栈顶
ID
的占用时间加上time-lastTime
,不出栈 - 更新
time,type,ID
后入栈
- 栈顶
- 上一个状态为
end
- 如果
time-lastTime != 1
(说明当前状态和上一个状态中间的时间非显性的由栈顶id
使用了)- 栈顶
ID
的占用时间加上time-lastTime-1
,不出栈
- 栈顶
- 更新
time,type,ID
后入栈
- 如果
- 上一个状态为
- 当前状态为
end
- 上一个状态为
start
(此时,上一个状态和这一个状态的id
一定相同,故时间加一)- 栈顶
ID
的占用时间加上time-lastTime+1
,出栈 - 更新
time,type,ID
- 栈顶
- 上一个状态为
end
- 栈顶
ID
的占用时间加上time-lastTime
,出栈 - 更新
time,type,ID
- 栈顶
- 上一个状态为
public int[] exclusiveTime(int n, List<String> logs) {
Stack<Integer> stack = new Stack<>();
int[] result = new int[n];
if (logs.size() == 0)
return result;
int firstIndex;
int lastIndex;
int lastTime = 0;
int lastId = -1;
int lastType = 0;
for (String log:logs) {
firstIndex = log.indexOf(":");
lastIndex = log.lastIndexOf(":");
int id = Integer.parseInt(log.substring(0, firstIndex));
int time = Integer.parseInt(log.substring(lastIndex + 1, log.length()));
int type = "end".equals(log.substring(firstIndex + 1, lastIndex)) ? -1 : 1;//end为-1,start为1
if (type == 1) {
if (lastType == 1) {
result[stack.peek()] += time - lastTime;
} else if (lastType == -1){
if (!stack.empty() && time-lastId!=1){
result[stack.peek()] += time - lastTime - 1;
}
}
lastTime = time;
lastType = type;
lastId = id;
stack.push(id);
} else {
if (lastType == -1)
result[stack.pop()] += time - lastTime;
else
result[stack.pop()] += time - lastTime + 1;
lastTime = time;
lastType = type;
lastId = id;
}
}
return result;
}