[Leetcode]636. Exclusive Time of Functions
链接:LeetCode636
给一个个函数运行记录的log数组,表示非抢占式CPU调用函数的情况,即同时只能运行一个函数。格式为,求每个函数占用cpu的总时间。
Input:
n =
logs =
Output:
相关标签:栈
首先要弄明白一点:当遍历到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 函数的独家时间
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)