636. Exclusive Time of Functions

Posted jxr041100

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

 

struct Log
{
    int id;
    string s;
    int time;
    Log(int _id,string _s,int _time)
    {
        id = _id;
        s = _s;
        time = _time;     
    }
};

class Solution {
public:
    vector<int> exclusiveTime(int n, vector<string>& logs) {
        stack<Log> q;
        vector<int> res(n);
        for(auto log:logs)
        {
           vector<string> parsed = parse_log(log);
           int id =  stoll(parsed[0]);
           string s = parsed[1];
           int time = stoll(parsed[2]);
           Log curr_log(id,s,time);
           if(q.empty()||s=="start") q.push(curr_log);
           else
           {
               int curr_start_time = q.top().time;
               q.pop();
               int time_spent = time-curr_start_time+1;
               res[id] += time_spent;
                //下面这行的逻辑关系我刚开始没有想到,非常的优美。 
                if(!q.empty()) 
                    res[q.top().id]= res[q.top().id]-time_spent;   
           }
        }
        return res;   
    }
private:
vector<string> parse_log(string log)
{
     vector<string>res;
     string token;
     log +=":";
     stringstream is(log);
     while(getline(is,token,:))
        res.push_back(token);
     return res;                
}
    

};

 

以上是关于636. Exclusive Time of Functions的主要内容,如果未能解决你的问题,请参考以下文章

636. Exclusive Time of Functions

[leetcode-636-Exclusive Time of Functions]

Leetcode 636: Exclusive Time of Functions

[LeetCode] Exclusive Time of Functions 函数的独家时间

1.1 VMware 一步一步创建虚拟机

APUE: time-of-check-to-time-of-use(TOCTTOU)