1. 程式人生 > >582. Kill Process殺死所有子代

582. Kill Process殺死所有子代

public fir pan 算法思想 child uniq 正常 () shm

[抄題]:

Given n processes, each process has a unique PID (process id) and its PPID (parent process id).

Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.

We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.

Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.

Example 1:

Input: 
pid =  [1, 3, 10, 5]
ppid = [3, 0, 5, 3]
kill = 5
Output: [5,10]
Explanation: 
           3
         /           1     5
             /
            10
Kill 5 will also kill 10.

[暴力解法]:

時間分析:

空間分析:

[優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

kill = 0時,pid直接返回

[思維問題]:

以為要從中序構建樹。但是構建出來之後還是

需要dfs,來找出所有子代。

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

一對的數據結構,就要用hashmap了,不能每次都忘記。

[一句話思路]:

  1. 先把主要的pid都添加一遍,最後再一起dfs
  2. 題目已經制定了pid是unique的,所以用list即可,不需要set

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

構建出來之後還是需要dfs,來找出所有子代

[復雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:叠代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

[是否頭一次寫此類driver funcion的代碼] :

[潛臺詞] :

技術分享圖片
class Solution {
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        //initialization: map
        List<Integer> result = new ArrayList<Integer>();
        HashMap<Integer, Set<Integer>> map = new HashMap<>();
        int n = pid.size();
        
        //corner case
        if (kill == 0) return pid;
        //put all the pid and ppid into the map
        for (int i = 0; i < n; i++) {
            //if no key, add new set
            if (map.get(ppid.get(i)) == null)
                map.put(ppid.get(i), new HashSet<Integer>());
            //add value
            map.get(ppid.get(i)).add(pid.get(i));
        }
        
        //dfs
        dfs(kill, map, result);
 
        //return
        return result;
    }
    
    public void dfs(int pid, HashMap<Integer, Set<Integer>> map, List<Integer> result) {
        //add pid to result
        result.add(pid);
        
        //exit when !get(pid)
        if (!map.containsKey(pid)) return ;
        
        //expand to child
        Set<Integer> children = map.get(pid);
        for (int child : children) {
            dfs(child, map, result);
        }
    }
}
View Code

582. Kill Process殺死所有子代