Simulation Exclusive Time of Functions

2018-04-28 14:10:33

Problem Description:

Problem solving:

Personally, I think this is a good simulation question. The main idea of ​​the title is to give a single-threaded processor and run a function on the processor, but there is a calling relationship in the function, which can be to call other functions, or it can be a recursive call By yourself, give the start and end time of each function through logs, and ask what is the actual running time of each function. Logs are given in the order of timestamps, not function names. The final result needs to be sorted according to the size of the function name.

Why is this a simulation question? Because the calling relationship of a function is essentially the push and pop from the stack. Using the data structure of the stack can simulate the calling relationship of the function well. Through this question, we can better understand the The calling relationship between functions in the actual running process.

    public int[] exclusiveTime(int n, List<String> logs) {
        int[] res = new int[n];
        Stack<Integer> s = new Stack<>();
        int prev = 0;
        for (String log : logs) {
            String[] ls = log.split(":");
            int idx = Integer.valueOf(ls[0]);
            int t = Integer.valueOf(ls[2]);
            if (ls[1].equals("start")) {
                if (!s.isEmpty()) res[s.peek()] += t - prev;
                s.push(idx);
                prev = t;
            }
            else {
                if (!s.isEmpty()) res[s.peek()] += t - prev + 1;
                s.pop();
                prev = t + 1;
            }
        }
        return res;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325024486&siteId=291194637