LC.P636[函数的独占时间]

方法一:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
int[] ans = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
int cur = -1;
for (String log : logs) {
String[] s = log.split(":");
int index = Integer.parseInt(s[0]), timestamp = Integer.parseInt(s[2]);
if (s[1].equals("start")) {
if (!stack.isEmpty()) ans[stack.peek()] += timestamp - cur;
stack.push(index);
cur = timestamp;
} else {
ans[stack.pop()] += timestamp - cur + 1;
cur = timestamp + 1;
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$