[LeetCode]636. Exclusive Time of Functions

来源:互联网 发布:线切割锥度怎样编程 编辑:程序博客网 时间:2024/06/05 16:14

https://leetcode.com/problems/exclusive-time-of-functions/#/description

给一个log数组,表示非抢占式CPU调用function的情况。格式为id:start or end:time

求每个func占用cpu的总时间




用stack保存当前还在调用栈内的func的id,pre记录前序时间。遇到start要push进入stack,遇到end要pop

public class Solution {    public int[] exclusiveTime(int n, List<String> logs) {        int[] res = new int[n];        Stack<Integer> stack = new Stack();        int pre = 0;        for (String log : logs) {            String[] arr = log.split(":");            if (arr[1].equals("start")) {                if (!stack.isEmpty()) {                    res[stack.peek()] += Integer.parseInt(arr[2]) - pre;                }                stack.push(Integer.parseInt(arr[0]));                pre = Integer.parseInt(arr[2]);            } else {                res[stack.pop()] += Integer.parseInt(arr[2]) - pre + 1;                pre = Integer.parseInt(arr[2]) + 1;            }        }        return res;    }}


原创粉丝点击