636. Exclusive Time of Functions
On a single threaded CPU, we execute some functions. Each function has a unique id between 0
and N-1
.
We store logs in timestamp order that describe when a function is entered or exited.
Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}"
. For example, "0:start:3"
means the function with id 0
started at the beginning of timestamp 3
. "1:end:2"
means the function with id 1
ended at the end of timestamp 2
.
A function's exclusive time is the number of units of time spent in this function. Note that this does not include any recursive calls to child functions.
The CPU is single threaded which means that only one function is being executed at a given time unit.
Return the exclusive time of each function, sorted by their function id.
分析:
因为开始和结束永远是一对的。而且如果当前是结束的话,之前一个一定是开始。所以,我们用stack来存之前的log,拿到end就pop,然后更新当前function的执行时间以及调用这个function
的执行时间。
1 class Solution { 2 public int[] exclusiveTime(int n, List<String> logs) { 3 Stack<Log> stack = new Stack<>(); 4 int[] result = new int[n]; 5 for (String content : logs) { 6 Log log = new Log(content); 7 if (log.isStart) { 8 stack.push(log); 9 } else { 10 Log top = stack.pop(); 11 int runningTime = log.time - top.time + 1; 12 result[top.id] += runningTime; 13 if (!stack.isEmpty()) { 14 result[stack.peek().id] -= runningTime; // the reason we need to deduct runningtime is this runningtime peroid is occupied by the previously executed function 15 } 16 } 17 } 18 return result; 19 } 20 21 public static class Log { 22 public int id; 23 public boolean isStart; 24 public int time; 25 26 public Log(String content) { 27 String[] strs = content.split(":"); 28 id = Integer.valueOf(strs[0]); 29 isStart = strs[1].equals("start"); 30 time = Integer.valueOf(strs[2]); 31 } 32 } 33 }