[LeetCode] 636. Exclusive Time of Functions 函数的独家时间
Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions.
Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.
A log is a string has this format : function_id:start_or_end:timestamp
. For example, "0:start:0"
means function 0 starts from the very beginning of time 0. "0:end:0"
means function 0 ends to the very end of time 0.
Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id.
Example 1:
Input: n = 2 logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"] Output:[3, 4] Explanation: Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.
Note:
- Input logs will be sorted by timestamp, NOT log id.
- Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0.
- Two functions won't start or end at the same time.
- Functions could be called recursively, and will always end.
- 1 <= n <= 100
给一个n个函数运行记录的log数组,表示非抢占式CPU调用函数的情况,即同时只能运行一个函数。格式为id:start or end:time,求每个函数占用cpu的总时间。
解法:栈,用stack保存当前还在还没结束的function的(id,start)。遇到是start的log时,计算栈顶函数的时间,然后把当前函数push进stack;遇到是end的就pop出stack的最近一个元素,并计算此function的运行时间。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public int [] exclusiveTime( int n, List<String> logs) { int [] res = new int [n]; Stack<Integer> stack = new Stack<>(); int prevTime = 0 ; for (String log : logs) { String[] parts = log.split( ":" ); if (!stack.isEmpty()) res[stack.peek()] += Integer.parseInt(parts[ 2 ]) - prevTime; prevTime = Integer.parseInt(parts[ 2 ]); if (parts[ 1 ].equals( "start" )) stack.push(Integer.parseInt(parts[ 0 ])); else { res[stack.pop()]++; prevTime++; } } return res; } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Time: O(n) # Space: O(n) class Solution( object ): def exclusiveTime( self , n, logs): """ :type n: int :type logs: List[str] :rtype: List[int] """ result = [ 0 ] * n stk, prev = [], 0 for log in logs: tokens = log.split( ":" ) if tokens[ 1 ] = = "start" : if stk: result[stk[ - 1 ]] + = int (tokens[ 2 ]) - prev stk.append( int (tokens[ 0 ])) prev = int (tokens[ 2 ]) else : result[stk.pop()] + = int (tokens[ 2 ]) - prev + 1 prev = int (tokens[ 2 ]) + 1 return result |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Solution( object ): def exclusiveTime( self , n, logs): """ :type n: int :type logs: List[str] :rtype: List[int] """ ans = [ 0 ] * n stack = [] for log in logs: fid, soe, tmp = log.split( ':' ) fid, tmp = int (fid), int (tmp) if soe = = 'start' : if stack: topFid, topTmp = stack[ - 1 ] ans[topFid] + = tmp - topTmp stack.append([fid, tmp]) else : ans[stack[ - 1 ][ 0 ]] + = tmp - stack[ - 1 ][ 1 ] + 1 stack.pop() if stack: stack[ - 1 ][ 1 ] = tmp + 1 return ans |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def exclusiveTime( self , N, logs): ans = [ 0 ] * N stack = [] prev_time = 0 for log in logs: fn, typ, time = log.split( ':' ) fn, time = int (fn), int (time) if typ = = 'start' : if stack: ans[stack[ - 1 ]] + = time - prev_time stack.append(fn) prev_time = time else : ans[stack.pop()] + = time - prev_time + 1 prev_time = time + 1 return ans |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def exclusiveTime( self , N, logs): ans = [ 0 ] * N #stack = SuperStack() stack = [] for log in logs: fn, typ, time = log.split( ':' ) fn, time = int (fn), int (time) if typ = = 'start' : stack.append(time) else : delta = time - stack.pop() + 1 ans[fn] + = delta #stack.add_across(delta) stack = [t + delta for t in stack] #inefficient return ans |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #include <iostream> #include <vector> #include <stack> #include <sstream> #include <cassert> using namespace std; 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 temp, temp2, temp3; getline(ss, temp, ':' ); getline(ss, temp2, ':' ); getline(ss, temp3, ':' ); Log item = {stoi(temp), temp2, stoi(temp3)}; if (item.status == "start" ) { st.push(item); } else { assert (st.top().id == item.id); int time_added = item.timestamp - st.top().timestamp + 1; times[item.id] += time_added; st.pop(); if (!st.empty()) { assert (st.top().status == "start" ); times[st.top().id] -= time_added; } } } return times; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Solution { public : vector< int > exclusiveTime( int n, vector<string>& logs) { vector< int > res(n, 0); stack< int > st; int preTime = 0; for (string log : logs) { int found1 = log .find( ":" ); int found2 = log .find_last_of( ":" ); int idx = stoi( log .substr(0, found1)); string type = log .substr(found1 + 1, found2 - found1 - 1); int time = stoi( log .substr(found2 + 1)); if (!st.empty()) { res[st.top()] += time - preTime; } preTime = time ; if (type == "start" ) st.push(idx); else { auto t = st.top(); st.pop(); ++res[t]; ++preTime; } } return res; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public : vector< int > exclusiveTime( int n, vector<string>& logs) { vector< int > res(n, 0); stack< int > st; int preTime = 0, idx = 0, time = 0; char type[10]; for (string log : logs) { sscanf ( log .c_str(), "%d:%[^:]:%d" , &idx, type, & time ); if (type[0] == 's' ) { if (!st.empty()) { res[st.top()] += time - preTime; } st.push(idx); } else { res[st.top()] += ++ time - preTime; st.pop(); } preTime = time ; } return res; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)