链接:LeetCode636
给一个\(n\)个函数运行记录的log数组,表示非抢占式CPU调用函数的情况,即同时只能运行一个函数。格式为\(id:start\ or\ end:time\),求每个函数占用cpu的总时间。
Input:
n = \(2\)
logs = \(["0:start:0","1:start:2","1:end:5","0:end:6"]\)
Output: \([3, 4]\)
相关标签:栈
首先要弄明白一点:当遍历到logs中的某个字符串时,无论它是begin还是end,当前位于栈顶的元素都会占用 “当前字符串的timePoint-之前字符串的timePoint”(或+1) 时间。
因为如果当前遍历到的字符串是start,那么栈顶元素就是之前start了还没结束的function,在 当前时间点 和 上一个时间点 之间的这段时间,是被栈顶元素占用的,占用了 “当前字符串的timePoint-之前字符串的timePoint” 时间。
算法的关键在于:拿到上一个log的 start/stop time 设为prev,再拿到当前 log 的 start/stop time ,计算出两个time之间的时间差。这也可以同比为,每次计算一个log的占用时间delta,将栈里面的数都减去delta。
python:
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: res = [0 for i in range(n)] stack = [] for i,log in enumerate(logs): function_id,flag,timestamp = log.split(':') function_id,timestamp = int(function_id),int(timestamp) if flag == 'start': stack.append(timestamp) elif flag == 'end': delta = timestamp - stack.pop() + 1 res[function_id] += delta stack = [x+delta for x in stack] return res
C++:
struct Log{ int id; string status; int timestamp; }; class Solution { public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> times(n,0); stack<Log> st; for (string log:logs){ stringstream ss(log); string temp1,temp2,temp3; getline(ss,temp1,':'); getline(ss,temp2,':'); getline(ss,temp3,':'); Log item = {stoi(temp1),temp2,stoi(temp3)}; if (item.status == "start"){ st.push(item); } else{ int delta = item.timestamp - st.top().timestamp + 1; times[item.id] += delta; st.pop(); if(!st.empty()){ times[st.top().id] -= delta; } } } return times; } };
参考:
leetcode 636. Exclusive Time of Functions
[LeetCode] 636. Exclusive Time of Functions 函数的独家时间