明报仙台今日下雪 辐射碘将重回地面 ZZ# Stock
D*0
1 楼
636. Exclusive Time of Functions
Input:
n = 2
logs =
["0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"]
Output:[3, 4]
这道题目,很有意思。
单线程求每个函数执行的总时间。
一共有
start end start end
start start end end
两种情况。
需要注意,开始时间是 第i秒的开始,结束时间是第i秒的最后。
class Solution {
public int[] exclusiveTime(int n, List logs) {
Stack stack = new Stack<>();
int[] res = new int[n];
String[] sa = logs.get(0).split(":");
int prev = Integer.parseInt(sa[2]);
stack.push(Integer.parseInt(sa[0]));
for (int i = 1; i < logs.size(); i++) {
sa = logs.get(i).split(":");
if (sa[1].equals("start")) {
if (!stack.isEmpty()) {
res[stack.peek()] += Integer.parseInt(sa[2]) - prev;
}
stack.push(Integer.parseInt(sa[0]));
prev = Integer.parseInt(sa[2]);
} else {
res[stack.pop()] += Integer.parseInt(sa[2]) - prev + 1;
prev = Integer.parseInt(sa[2]) + 1;
}
}
return res;
}
}
Input:
n = 2
logs =
["0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"]
Output:[3, 4]
这道题目,很有意思。
单线程求每个函数执行的总时间。
一共有
start end start end
start start end end
两种情况。
需要注意,开始时间是 第i秒的开始,结束时间是第i秒的最后。
class Solution {
public int[] exclusiveTime(int n, List
Stack
int[] res = new int[n];
String[] sa = logs.get(0).split(":");
int prev = Integer.parseInt(sa[2]);
stack.push(Integer.parseInt(sa[0]));
for (int i = 1; i < logs.size(); i++) {
sa = logs.get(i).split(":");
if (sa[1].equals("start")) {
if (!stack.isEmpty()) {
res[stack.peek()] += Integer.parseInt(sa[2]) - prev;
}
stack.push(Integer.parseInt(sa[0]));
prev = Integer.parseInt(sa[2]);
} else {
res[stack.pop()] += Integer.parseInt(sa[2]) - prev + 1;
prev = Integer.parseInt(sa[2]) + 1;
}
}
return res;
}
}