|
6 | 6 |
|
7 | 7 | public class _636 {
|
8 | 8 | public static class Solution1 {
|
9 |
| - /** |
10 |
| - * Based on the example, it's difficult to see how function 2 executes 4 units of time, actually |
11 |
| - * we can add 1 to all end times to make it easier to understand and AC'ed. |
12 |
| - */ |
13 | 9 | public int[] exclusiveTime(int n, List<String> logs) {
|
14 | 10 | /**Stack is the way to go:
|
15 |
| - * we keep pushing the logId onto the stack whenever we just encounter this logId's start timestamp, |
16 |
| - * we'll pop this logId only when we encounter this logId's end timestamp. |
17 |
| - * Meanwhile, we keep a counter called prevTime, |
18 |
| - * whenever the stack is not empty, we'll always deduct prevTime from the last logId on the stack.*/ |
| 11 | + * 1. we keep pushing the logId onto the stack whenever we just encounter this logId's start timestamp, |
| 12 | + * 2. we'll pop this logId only when we encounter this logId's end timestamp. |
| 13 | + * 3. Meanwhile, we keep a counter called prevTime, |
| 14 | + * 4. whenever the stack is not empty, we'll always deduct prevTime from the last logId on the stack.*/ |
19 | 15 | Deque<Integer> stack = new LinkedList<>();
|
20 | 16 | int[] result = new int[n];
|
21 | 17 | int prevTime = 0;
|
22 | 18 | for (String log : logs) {
|
23 | 19 | String[] parts = log.split(":");
|
24 | 20 | if (!stack.isEmpty()) {
|
25 |
| - result[stack.peek()] += Integer.parseInt(parts[2]) - prevTime; |
| 21 | + result[stack.peekLast()] += Integer.parseInt(parts[2]) - prevTime; |
26 | 22 | }
|
27 | 23 | prevTime = Integer.parseInt(parts[2]);
|
28 | 24 | if (parts[1].equals("start")) {
|
29 |
| - stack.addFirst(Integer.parseInt(parts[0]));//i.e. stack.push() |
| 25 | + stack.addLast(Integer.parseInt(parts[0])); |
30 | 26 | } else {
|
| 27 | + //remember to have result plus 1, i.e. when a task starts at 2, ends at 5, it should be 5 -2 + 1 = 4 |
31 | 28 | prevTime++;
|
32 |
| - //remember to have result pluse 1 to match the problem AC criteria |
33 |
| - result[stack.pollFirst()]++;//i.e. stack.pop() |
| 29 | + result[stack.pollLast()]++; |
34 | 30 | }
|
35 | 31 | }
|
36 | 32 | return result;
|
|
0 commit comments