|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +# Given the running logs of n functions that are executed |
| 5 | +# in a nonpreemptive single threaded CPU, find the exclusive time of these functions. |
| 6 | +# |
| 7 | +# Each function has a unique id, start from 0 to n-1. |
| 8 | +# A function may be called recursively or by another function. |
| 9 | +# |
| 10 | +# A log is a string has this format : function_id:start_or_end:timestamp. |
| 11 | +# For example, "0:start:0" means function 0 starts from the very beginning of time 0. |
| 12 | +# "0:end:0" means function 0 ends to the very end of time 0. |
| 13 | +# |
| 14 | +# Exclusive time of a function is defined as the time spent within this function, |
| 15 | +# the time spent by calling other functions should not be considered as |
| 16 | +# this function's exclusive time. |
| 17 | +# You should return the exclusive time of each function sorted by their function id. |
| 18 | +# |
| 19 | +# Example 1: |
| 20 | +# Input: |
| 21 | +# n = 2 |
| 22 | +# logs = |
| 23 | +# ["0:start:0", |
| 24 | +# "1:start:2", |
| 25 | +# "1:end:5", |
| 26 | +# "0:end:6"] |
| 27 | +# Output:[3, 4] |
| 28 | +# |
| 29 | +# Explanation: |
| 30 | +# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. |
| 31 | +# Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. |
| 32 | +# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. |
| 33 | +# So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. |
| 34 | +# |
| 35 | +# Note: |
| 36 | +# Input logs will be sorted by timestamp, NOT log id. |
| 37 | +# Your output should be sorted by function id, |
| 38 | +# which means the 0th element of your output corresponds to the exclusive time of function 0. |
| 39 | +# Two functions won't start or end at the same time. |
| 40 | +# Functions could be called recursively, and will always end. |
| 41 | +# 1 <= n <= 100 |
| 42 | + |
| 43 | +class Solution(object): |
| 44 | + def exclusiveTime(self, n, logs): |
| 45 | + """ |
| 46 | + :type n: int |
| 47 | + :type logs: List[str] |
| 48 | + :rtype: List[int] |
| 49 | + """ |
| 50 | + result = [0] * n |
| 51 | + stk, prev = [], 0 |
| 52 | + for log in logs: |
| 53 | + tokens = log.split(":") |
| 54 | + if tokens[1] == "start": |
| 55 | + if stk: |
| 56 | + result[stk[-1]] += int(tokens[2]) - prev |
| 57 | + stk.append(int(tokens[0])) |
| 58 | + prev = int(tokens[2]) |
| 59 | + else: |
| 60 | + result[stk.pop()] += int(tokens[2]) - prev + 1 |
| 61 | + prev = int(tokens[2]) + 1 |
| 62 | + return result |
0 commit comments