美文网首页
栈问题 LC636 - Exclusive Time of Fu

栈问题 LC636 - Exclusive Time of Fu

作者: 风烨 | 来源:发表于2017-11-12 22:20 被阅读0次

总结一下注意两点

  1. 区分start/end,如果是end则记得+1(因为要包含end stamp),如果是start则记得把process id 丢入栈中
  2. 每读取一条log,都要记录stamp走到了哪里。
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] res = new int[n];
        Stack<Integer> stack = new Stack<>();
        int prevStamp = 0;
        String endString = "end";
        for (String log : logs) {   
            String[] detail = log.split(":");
            int id = Integer.parseInt(detail[0]);
            String action = detail[1];
            int stamp = Integer.parseInt(detail[2]);
            //stack cannot be empty for valid logs
            if(endString.equals(action)) {
                int prevId = stack.pop();
                // include the ending timestamp and suspend prev process
                res[prevId] += (++stamp - prevStamp);
            } else {//start time log
                // suspend prev process and start current process and record the prev running time
                if(!stack.isEmpty()) res[stack.peek()] += (stamp - prevStamp); 
                stack.push(id);//push current process id in stack
            }
            prevStamp = stamp;   
        }
        return res;
    }

相关文章

网友评论

      本文标题:栈问题 LC636 - Exclusive Time of Fu

      本文链接:https://www.haomeiwen.com/subject/qbgomxtx.html