leetcode 636. Exclusive Time of Functions | 636. 函数的独占时间(Stack)
生活随笔
收集整理的這篇文章主要介紹了
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<String> logs) {Stack<Integer> 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;} }總結
以上是生活随笔為你收集整理的leetcode 636. Exclusive Time of Functions | 636. 函数的独占时间(Stack)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 907. Sum of
- 下一篇: leetcode 638. Shoppi