【Leetcode】582. Kill Process

題目地址:

https://leetcode.com/problems/kill-process/

參考https://blog.csdn.net/qq_46105170/article/details/106309633。代碼如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        List<Integer> res = new ArrayList<>();
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int i = 0; i < ppid.size(); i++) {
            graph.putIfAbsent(ppid.get(i), new ArrayList<>());
            graph.get(ppid.get(i)).add(pid.get(i));
        }
        
        dfs(kill, graph, res);
        return res;
    }
    
    private void dfs(int cur, Map<Integer, List<Integer>> graph, List<Integer> res) {
        res.add(cur);
        if (graph.containsKey(cur)) {
            for (int next : graph.get(cur)) {
                dfs(next, graph, res);
            }
        }
    }
}

時空複雜度O(V+E)O(V+E)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章