The exclusive time of the function

Record each function by running the length of time, the input example [0: start: “0”, “1: start: 2”, “1: end: 5”, “0: end: 6”]

The problem solving code

We can use the stack to record each id, start the stack, end the stack, get the interval value, use the next node minus the beginning of the previous node is the first half of the interval, the second half of the interval use the previous node end point range minus the end of the current point node

  1. [“0:start:0″,”1:start:2″,”1:end:5″,”0:end:6”]
  2. [0 (start), 1, 2 (start), three, four, five (end), 6 (end)]
  3. Id = 0; id = 1; id = 1; id = 1; id = 1;
  4. The final result is [3, 4]
var exclusiveTime = function(n, logs) {
  let ans = new Array(n).fill(0);
  let stack = []; // Record the stack of task ID
  let pre = 0; // Record the previous time
  for (let i = 0; i < logs.length; i++) {
    const element = logs[i];
    const pos = element.split(":");
    let [id, status, time] = pos;
    time = Number(time);
    if (status === "start") { // The task begins
      if (stack.length) {
        ans[stack[stack.length - 1]] += time - pre; // Record the numbered time period at the top of the stack
      }
      pre = time;
      stack.push(id);
    } else { // The task is complete
      ans[id] += time - pre + 1; // If it is the end of the task, you should add the start time of the current ID + the end time between now and pre
      pre = time + 1; // Since pre is + 1, so + 1 is the correct value for the next loop, (time = 6, pre = 5,time - pre + 1 = 2); (time = 6, pre = 5,time - pre + 1 = 2)
      stack.pop(); // After processing a task, the current task is off the stack}}return ans; // Return an array of results
};
Copy the code