题目地址:
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) O(V+E)。
本文提供了一种解决LeetCode上'Kill Process'问题的方法,通过使用Java实现的深度优先搜索(DFS)算法,有效地找出并返回由指定PID及其所有子进程组成的进程树。代码利用HashMap构建父子进程关系图,再进行DFS遍历,最终返回所有要终止的进程ID列表。


被折叠的 条评论
为什么被折叠?



