总结一下注意两点
- 区分start/end,如果是end则记得+1(因为要包含end stamp),如果是start则记得把process id 丢入栈中
- 每读取一条log,都要记录stamp走到了哪里。
public int[] exclusiveTime(int n, List<String> logs) {
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
int prevStamp = 0;
String endString = "end";
for (String log : logs) {
String[] detail = log.split(":");
int id = Integer.parseInt(detail[0]);
String action = detail[1];
int stamp = Integer.parseInt(detail[2]);
//stack cannot be empty for valid logs
if(endString.equals(action)) {
int prevId = stack.pop();
// include the ending timestamp and suspend prev process
res[prevId] += (++stamp - prevStamp);
} else {//start time log
// suspend prev process and start current process and record the prev running time
if(!stack.isEmpty()) res[stack.peek()] += (stamp - prevStamp);
stack.push(id);//push current process id in stack
}
prevStamp = stamp;
}
return res;
}
网友评论