|
| 1 | +/** |
| 2 | + * 636. Exclusive Time of Functions |
| 3 | + * https://leetcode.com/problems/exclusive-time-of-functions/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * On a single-threaded CPU, we execute a program containing n functions. Each function has a |
| 7 | + * unique ID between 0 and n-1. |
| 8 | + * |
| 9 | + * Function calls are stored in a call stack: when a function call starts, its ID is pushed |
| 10 | + * onto the stack, and when a function call ends, its ID is popped off the stack. The function |
| 11 | + * whose ID is at the top of the stack is the current function being executed. Each time a |
| 12 | + * function starts or ends, we write a log with the ID, whether it started or ended, and the |
| 13 | + * timestamp. |
| 14 | + * |
| 15 | + * You are given a list logs, where logs[i] represents the ith log message formatted as a string |
| 16 | + * "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call |
| 17 | + * with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function |
| 18 | + * call with function ID 1 ended at the end of timestamp 2. Note that a function can be called |
| 19 | + * multiple times, possibly recursively. |
| 20 | + * |
| 21 | + * A function's exclusive time is the sum of execution times for all function calls in the program. |
| 22 | + * For example, if a function is called twice, one call executing for 2 time units and another |
| 23 | + * call executing for 1 time unit, the exclusive time is 2 + 1 = 3. |
| 24 | + * |
| 25 | + * Return the exclusive time of each function in an array, where the value at the ith index |
| 26 | + * represents the exclusive time for the function with ID i. |
| 27 | + */ |
| 28 | + |
| 29 | +/** |
| 30 | + * @param {number} n |
| 31 | + * @param {string[]} logs |
| 32 | + * @return {number[]} |
| 33 | + */ |
| 34 | +var exclusiveTime = function(n, logs) { |
| 35 | + const stack = []; |
| 36 | + const result = new Array(n).fill(0); |
| 37 | + let previousTime = 0; |
| 38 | + |
| 39 | + for (const log of logs) { |
| 40 | + const [id, action, time] = log.split(':'); |
| 41 | + const currentTime = +time; |
| 42 | + |
| 43 | + if (action === 'start') { |
| 44 | + if (stack.length) { |
| 45 | + result[stack[stack.length - 1]] += currentTime - previousTime; |
| 46 | + } |
| 47 | + stack.push(+id); |
| 48 | + previousTime = currentTime; |
| 49 | + } else { |
| 50 | + result[stack.pop()] += currentTime - previousTime + 1; |
| 51 | + previousTime = currentTime + 1; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return result; |
| 56 | +}; |
0 commit comments