582. Kill Process杀死所有子代

[抄题]:

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);
}
}
}
上一篇:[LeetCode] 582. Kill Process 终止进程


下一篇:Maven上传本地jar