LeetCode636. Exclusive Time of Functions

版权声明:转载请注明出处。我的GitHub是:https://github.com/YaokaiYang-assaultmaster,欢迎来访。 https://blog.csdn.net/Yaokai_AssultMaster/article/details/78227788

One-pass solution.

During iterating through the input logs, there are 4 possible conditions:

  1. Previous log is “start”, current log is “start”. This means that either the previous function is calling some other function or it’s calling itself recursively. However, it makes no difference for those 2 cases, we just add the time gap between these 2 start to the total exclusive time of previous function.
  2. Previous log is “start”, current log is “end”. This means that current function runs to an end and haven’t call any other functions including itself. In this case we simply add this time gap to the total exclusive time of current function. Note this have a different calcuiating method, which is endTime - startTime + 1.
  3. Previous log is “end”, current log is “start”. This means that a previous function call is completed and the original function is running and is calling another function. Thus this time gap should be added to the original outer function that performs the call. However, there is another case for this as well. If there is no function performs the call, that means during this time gap the CPU is idle, and we should just ignore this time gap.
  4. Previous log is “end”, current log is “end”. This means that a previous function call is end, and the function that performs the call is completed as well. Thus this time gap should be added to the outer function that performs the call.

Summarize them up, we get the following solution.

This algorithm runs in O(n)time, O(n) space worst case for length-n input.

class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] ret = new int[n];
        Deque<Integer> deque = new ArrayDeque<>();
        String[] log = logs.get(0).split(":");
        deque.push(Integer.parseInt(log[0]));
        int prevTime = Integer.parseInt(log[2]);
        for (int i = 0; i < logs.size(); i++) {
            log = logs.get(i).split(":");
            int time = Integer.parseInt(log[2]);
            if (log[1].equals("start")) {
                if (!deque.isEmpty()) {
                    ret[deque.peek()] += (time - prevTime);
                }
                prevTime = time;
                deque.push(Integer.parseInt(log[0]));
            } else { // "end"
                ret[deque.pop()] += (time - prevTime + 1);
                prevTime = time + 1;
            }
        }

        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/Yaokai_AssultMaster/article/details/78227788