Exclusive Time of Functions

 

1.解析 

题目大意,计算每一个函数执行的时间。

2.分析

题目看起来蛮简单的,但其实不然,最难理解的部分,就是在"end"状态这里,实际上,当检测到"end"状态的时候,不只是当前对应的id的函数会执行一个单位的时间,(这里主要是方便处理而已)上一个函数也会执行一个单位,然后上一个函数执行的起始时间要加1,其他部分就比较容易理解啦,利用一个栈保存当前最新执行的函数id,当检测到一个新的"start"状态,说明碰到一个新的函数,放在栈顶。具体实现参考如下:

class Solution {
public:
	vector<int> exclusiveTime(int n, vector<string>& logs) {
		vector<int> res(n);
        stack<int> st;
        int idx, cur, pre = 0; //pre----上一个时间 cur----当前的时间
        string status;
        for (auto log : logs){
            divideStr(log, idx, cur, status); //将当前的字符串划分成函数编号,状态和时间
            if (!st.empty()){ //计算上一个函数的执行时间
                res[st.top()] += cur - pre;
            }
            pre = cur;
            if (status == "start"){ //上一个执行的函数交出CPU使用权
                st.push(idx); //CPU开始执行现在的函数
            }
            else{ //检测到"end"状态,这步比较难理解
                res[st.top()]++; 
                st.pop(); //执行完上一个函数
                pre++; //上一个函数继续执行,只要CPU空闲,就可以认为上一个没有结束的函数在执行
            }
            
        }
        
        return res;
	}
	void divideStr(string log, int& idx, int& cur, string& status) { //引用可以保证返回多个值,划分字符串
		int pos1 = log.find(':');
		idx = atoi(log.substr(0, pos1).c_str());
		int pos2 = log.find(':', pos1 + 1);
		status = log.substr(pos1 + 1, pos2 - pos1 - 1);
        cur = atoi(log.substr(pos2+1).c_str());
	}
};

[1]https://www.cnblogs.com/grandyang/p/7244767.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章