栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode 636. Exclusive Time of Functions | 636. 函数的独占时间(Stack)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode 636. Exclusive Time of Functions | 636. 函数的独占时间(Stack)

题目

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

题解

类似于括号匹配问题,遍历 list,每一次来到新元素时,结算当前正在执行的函数已经运行的时间,累加到 result 数组的对应位置中。怎么知道当前正在执行哪个函数呢?维护函数调用栈即可,栈顶的元素就是正在执行的函数。

需要像括号匹配那样维护函数调用栈,即当遇到相同元素的 end 时,想象成括号闭合,则 pop 栈顶元素;如果不能闭合,则将当前看到的元素入栈。

需要注意的细节:start 时间点和 end 时间点的开闭区间不一样。

class Solution {
    public static final int ID = 0;
    public static final int STATUS = 1;
    public static final int TIMESTAMP = 2;
    public static final String START = "start";
    public static final String END = "end";

    public int[] exclusiveTime(int n, List logs) {
        Stack stack = new Stack<>(); // call stack (id)
        int[] result = new int[n];
        for (int i = 0; i < logs.size(); i++) {
            boolean paired = false;
            String[] curLog = logs.get(i).split(":");
            if (!stack.isEmpty()) {
                String[] preLog = logs.get(i - 1).split(":");
                Integer runningId = stack.peek();

                int diff = Integer.parseInt(curLog[TIMESTAMP]) - Integer.parseInt(preLog[TIMESTAMP]);
                if (preLog[STATUS].equals(START) && curLog[STATUS].equals(END)) diff += 1;
                if (preLog[STATUS].equals(END) && curLog[STATUS].equals(START)) diff -= 1;
                result[runningId] += diff;

                if (curLog[STATUS].equals(END) && Integer.parseInt(curLog[ID]) == runningId) { // 成功匹配
                    stack.pop();
                    paired = true;
                }
            }
            if (!paired) stack.push(Integer.parseInt(curLog[ID]));
        }
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/319371.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号