LeetCode 36. Exclusive Time of Functions

用栈模拟cpu的任务队列

注意:开始时间给的是某一秒钟的开始,结束时间给的是某一秒钟的结尾

class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        Stack<Pair<Integer,Integer>> cpu = new Stack<>();
        int len = logs.size();
        String []tem = logs.get(0).split(":");
        cpu.push(new Pair(Integer.valueOf(tem[0]),Integer.valueOf(tem[2])));
        int []ans = new int[n];
        int cur = Integer.valueOf(tem[2]);
        for(int i=1;i<len;i++){
            int flag = 1;
            tem = logs.get(i).split(":");
            Pair<Integer,Integer> pair = new Pair(0,0);
            if(cpu.empty())
                flag = 0;
            else 
                pair = cpu.peek();
            if(tem[1].equals("end")){
                ans[pair.getKey()]+=Integer.valueOf(tem[2]) + 1 - cur;
                cpu.pop();
                cur = Integer.valueOf(tem[2]) + 1;
            }else if(tem[1].equals("start")){
                if(flag == 1)
                    ans[pair.getKey()]+=Integer.valueOf(tem[2]) - cur;
                cpu.push(new Pair(Integer.valueOf(tem[0]),Integer.valueOf(tem[2])));
                cur = Integer.valueOf(tem[2]);
            }  
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Dale_zero/article/details/120194897