636. Exclusive Time of Functions

636. Exclusive Time of Functions

On a single threaded CPU, we execute some functions. Each function has a unique id between 0 and N-1.

We store logs in timestamp order that describe when a function is entered or exited.

Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means the function with id 0 started at the beginning of timestamp 3. "1:end:2"means the function with id 1 ended at the end of timestamp 2.

A function’s exclusive time is the number of units of time spent in this function. Note that this does not include any recursive calls to child functions.

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 the beginning of time 0, then it executes 2 units of time and reaches the end of time 1.
Now function 1 starts at the beginning of time 2, executes 4 units of time and ends at time 5.
Function 0 is running again at the beginning of time 6, and also ends at the end of time 6, thus executing for 1 unit of time. 
So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.

Note:

  1. 1 <= n <= 100
  2. Two functions won’t start or end at the same time.
  3. Functions will always log when they exit.

方法1:stack

思路:

每次遇到start,我们会将上一个还在运行的函数暂停,开始执行新的函数。截止此时上一个函数运行的时间是通过new_start - 栈顶时间计算的,累加到相应的id下。这个new_start同时被推入栈里。当遇到一个end,我们要从栈中pop出一个函数,并且计算其和栈顶函数的时间差,累加到栈顶函数的id上,同时修改下一个top的start时间为刚刚的结束时间。

易错点

  1. 时间的起点和终点含义不太一样,注意需要+1的地方
  2. 同一个函数可能会被层层嵌套:要叠加
class Solution {
public:
    vector<int> exclusiveTime(int n, vector<string>& logs) {
        vector<int> result(n);
        // id, start_time, accummulative
        stack<vector<int>> st;
        for (string s: logs) {
            auto stop1 = s.find(":");
            auto stop2 = s.find_last_of(":");
            int id = stoi(s.substr(0, stop1));
            string type = s.substr(stop1 + 1, stop2 - stop1 - 1);
            int time = stoi(s.substr(stop2 + 1));
            if (type == "start") {
                if(!st.empty()) {
                    st.top()[2] += time - st.top()[1];
                }
                st.push({id, time, 0});
            }
            else {
                auto top = st.top();
                st.pop();
                result[id] += time - top[1] + top[2] + 1;
                if (!st.empty()) st.top()[1] = time + 1;
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值