-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path636.java
More file actions
116 lines (103 loc) · 3.15 KB
/
636.java
File metadata and controls
116 lines (103 loc) · 3.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
__________________________________________________________________________________________________
sample 5 ms submission
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
int[] res = new int[n];
int start = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0, len = logs.size(); i < len; i++) {
Log log = new Log(logs.get(i));
if (log.isStart) {
if (!stack.isEmpty()) {
res[stack.peek()] += log.time - start;
}
stack.push(log.id);
start = log.time;
} else {
res[stack.pop()] += log.time - start + 1;
start = log.time + 1;
}
}
return res;
}
}
class Log {
int id;
int time;
boolean isStart;
Log(String logStr) {
int i = 0, len = logStr.length();
id = 0;
while (logStr.charAt(i) != ':') {
id = id * 10 + (logStr.charAt(i++) - '0');
}
if (logStr.charAt(++i) == 's') {
isStart = true;
i += 6;
} else {
isStart = false;
i += 4;
}
time = 0;
while (i < len) {
time = time * 10 + (logStr.charAt(i++) - '0');
}
}
}
__________________________________________________________________________________________________
sample 37004 kb submission
class Solution {
public int[] exclusiveTime(int n, List<String> l) {
List<Log> logs = l.stream().map(Log::new).collect(Collectors.toList());
Stack<Integer> frames = new Stack<>();
int curId = -1;
int curStart = -1;
int[] results = new int[n];
for (Log log : logs) {
if (log.isStart()) {
if (curId != -1) {
results[curId] += log.time() - curStart;
frames.push(curId);
}
curId = log.id();
curStart = log.time();
}
else {
results[curId] += log.time() - curStart + 1;
if (!frames.isEmpty()) {
curId = frames.pop();
curStart = log.time() + 1;
}
else {
curId = -1;
curStart = -1;
}
}
}
return results;
}
private class Log {
private int id;
private boolean isStart;
private int time;
public Log(String log) {
String[] tokens = log.split(":");
id = Integer.valueOf(tokens[0]);
isStart = tokens[1].equals("start");
time = Integer.valueOf(tokens[2]);
}
public int id() {
return id;
}
public int time() {
return time;
}
boolean isStart() {
return isStart;
}
boolean isEnd() {
return !isStart();
}
}
}
__________________________________________________________________________________________________