其他分享
首页 > 其他分享> > leetcode636-函数的独占时间

leetcode636-函数的独占时间

作者:互联网

函数的独占时间

使用栈记录调用过程。如果log为start,那么就加入堆栈。如果是end,则分两种情况:

  1. 栈不为空,意味着存在递归调用,那么说明当前的函数占用了上一个函数的使用时间,所以上一个函数要减去相应的时间,然后给当前函数增加时间
  2. 栈为空,则直接增加当前函数的时间
class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        Deque<int[]> stk = new ArrayDeque<>();
        int res[] = new int[n];
        for(String log : logs){
            int i0 = log.indexOf(":"), i1 = log.lastIndexOf(":");
            int index = Integer.parseInt(log.substring(0, i0)), time = Integer.parseInt(log.substring(i1+1));
            String op = log.substring(i0+1, i1);
            if(op.equals("start"))  stk.push(new int[]{index, time});
            else{
                int origin[] = stk.pop();
                if(!stk.isEmpty())  res[stk.peek()[0]] -= time-origin[1]+1;
                res[index] += time-origin[1]+1;
            }
        }
        return res;
    }
}

标签:log,独占,int,res,函数,stk,time,leetcode636
来源: https://www.cnblogs.com/xzh-yyds/p/16590035.html