forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKillProcess.java
More file actions
41 lines (32 loc) · 1.13 KB
/
KillProcess.java
File metadata and controls
41 lines (32 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/kill-process
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class KillProcess {
public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int process) {
Map<Integer, List<Integer>> adjList = buildAdjList(pid, ppid);
List<Integer> killed = new ArrayList<>();
kill(process, adjList, killed);
return killed;
}
private Map<Integer, List<Integer>> buildAdjList(List<Integer> pid, List<Integer> ppid) {
Map<Integer, List<Integer>> adjList = new HashMap<>();
for (int i = 0; i < pid.size(); i++) {
adjList.computeIfAbsent(ppid.get(i), __ -> new ArrayList<>()).add(pid.get(i));
}
return adjList;
}
private void kill(int process, Map<Integer, List<Integer>> adjList, List<Integer> killed) {
killed.add(process);
for (int child : adjList.getOrDefault(process, List.of())) {
kill(child, adjList, killed);
}
}
}