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:

  1. Input logs will be sorted by timestamp, NOT log id.
  2. Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0.
  3. Two functions won't start or end at the same time.
  4. Functions could be called recursively, and will always end.
  5. 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:

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:

# 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:

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:

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:  

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++:

#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++:

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++:  

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;
}
};

    

All LeetCode Questions List 题目汇总

[LeetCode] 636. Exclusive Time of Functions 函数的独家时间的更多相关文章

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

    Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find ...

  2. [leetcode]636. Exclusive Time of Functions函数独占时间

    Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find ...

  3. Leetcode 之 Exclusive Time of Functions

    636. Exclusive Time of Functions 1.Problem Given the running logs of n functions that are executed i ...

  4. 【LeetCode】636. Exclusive Time of Functions 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 栈 日期 题目地址:https://leetcode ...

  5. 【leetcode】636. Exclusive Time of Functions

    题目如下: 解题思路:本题和括号匹配问题有点像,用栈比较适合.一个元素入栈前,如果自己的状态是“start”,则直接入栈:如果是end则判断和栈顶的元素是否id相同并且状态是“start”,如果满足这 ...

  6. 636. Exclusive Time of Functions 进程的执行时间

    [抄题]: Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU ...

  7. 636. Exclusive Time of Functions

    // TODO: need improve!!! class Log { public: int id; bool start; int timestamp; int comp; // compasa ...

  8. [Swift]LeetCode636. 函数的独占时间 | Exclusive Time of Functions

    Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find ...

  9. Java实现 LeetCode 636 函数的独占时间(栈)

    636. 函数的独占时间 给出一个非抢占单线程CPU的 n 个函数运行日志,找到函数的独占时间. 每个函数都有一个唯一的 Id,从 0 到 n-1,函数可能会递归调用或者被其他函数调用. 日志是具有以 ...

随机推荐

  1. 补充拓展:CSS权重值叠加

    都知道CSS选择器有权重优先级,权重大的优先展示. 但部分人可能不清楚,权重值也是可以叠加计算的 <!DOCTYPE html> <html> <head> < ...

  2. git免密

    免账号密码输入 git clone https://lichuanfa%40gitcloud.com.cn:lcf13870752164@git.c.citic/Citic-Data/bigdata_ ...

  3. 通过vue-cli搭建vue项目

    一.搭建环境 安装node.js 从node.js官网下载并安装node,安装过程很简单,一路“下一步”就可以了.安装完成之后,打开命令行工具(win+r,然后输入cmd),输入 node -v,如下 ...

  4. Git学习笔记--实践(三)

    文中红色的文字(标为:## 插曲)是在Git学习/实践过程中,我个人遇到的一些问题,每个“## 插曲”之后,都有相应的解决方案. 一.创建版本库 版本库又名仓库,英文名repository,可简单的理 ...

  5. mongoDB新增数据库

    现在,如果我们想创建名为exampledb的数据库.只需运行以下命令并在数据库中保存一条记录.保存第一个示例后,将看到已创建新数据库. use tt 这样就创建了一个数据库,如果什么都不操作离开的话, ...

  6. [ARIA] Add aria-expanded to add semantic value and styling

    In this lesson, we will be going over the attribute aria-expanded. Instead of using a class like .op ...

  7. 17-ESP8266 SDK开发基础入门篇--TCP服务器 RTOS版,小试牛刀

    https://www.cnblogs.com/yangfengwu/p/11105466.html 现在开始写... lwip即可以用socket 的API  也可以用 netconn  的API实 ...

  8. 【区间DP】加分二叉树

    https://www.luogu.org/problemnew/show/P1040#sub 题目描述 设一个n个节点的二叉树tree的中序遍历为(1,2,3,…,n),其中数字1,2,3,…,n为 ...

  9. 时间time模块

    time模块: import time --时间模块 --time : 三种不同的时间格式,可以相互转换 时间戳(timestamp): --从1970年1月1日00:00:00开始按秒计算的偏移量 ...

  10. pycharm+gitee【代码上传下载】实战(windows详细版)

    pycharm+gitee环境搭建好以后应该如何进行代码上传下载操作呢?举几个例子,此文会一直更新 环境:2019社区版pycharm+gitee+git 系统:windows系统 一.代码上传功能 ...