【数据结构】算法 Exclusive Time of Functions 函数占用时间

Exclusive Time of Functions 函数占用时间

在单核单线程CPU上执行任务,任务id 从0n-1,任务会交替间断执行,

Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3,4]
 

计算每个任务的执行时的实际耗时。

思路

使用栈将每个start状态的任务入栈,并记录对应任务id的耗时。遇到end状态的任务就计算该任务的实际耗时并记录,再出栈。pre代表计算一个任务的开始指针,每扫描到一个任务,pre都会后移。

public int[] exclusiveTime(int n, List<String> logs) {
        int[] res = new int[n];
        Stack<Integer> vid = new Stack<>();
        for (int i = 0,pre =0; i < logs.size(); i++) {
            String[] split = logs.get(i).split(":");
            String idstr =split[0];
            String statusstr =split[1];
            String timestr =split[2];
            int id = Integer.valueOf(idstr);
            int timestamp = Integer.valueOf(timestr);
            if (!vid.isEmpty()){
                res[vid.peek()]+=timestamp-pre+("end".equals(statusstr)?1:0);
            }

            pre = timestamp +("end".equals(statusstr)?1:0);
            if ("start".equals(statusstr)){
                vid.push(id);
            }
            else{
                vid.pop();
            }
        }
        return res;
    }

Tag

stack

原文地址:https://www.cnblogs.com/dreamtaker/p/14605433.html