Java O(N) Stack Solution


  • 0
    M
        public int[] exclusiveTime(int n, List<String> logs) {
            if(n<0) n = 0;
            int[] res = new int[n];
            if(logs==null || logs.size()==0) return res;
            Deque<Integer> stack = new ArrayDeque<>();
            int time = 0;
            for(String log : logs){
                String[] curStr = log.split(":");
                int curTime = Integer.parseInt(curStr[2]);
                if(curStr[1].charAt(0)=='s'){ //start
                    if(!stack.isEmpty()) res[stack.peek()] += curTime - time;
                    time = curTime;
                    stack.push(Integer.parseInt(curStr[0]));
                } else { //end
                    res[stack.pop()] += curTime - time + 1;
                    time = curTime + 1;
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.