java 582. Kill Process(1st).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 582. Kill Process(1st).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        List<Integer> res = new ArrayList<Integer>();
        if (pid == null || ppid == null) return res;
        Map<Integer, List<Integer>> adjList = new HashMap<Integer, List<Integer>>();
        int len = pid.size();
        for (int i = 0; i < len; i++) {
            adjList.putIfAbsent(ppid.get(i), new ArrayList<Integer>());
            adjList.get(ppid.get(i)).add(pid.get(i));
        }
        
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(kill);
        while(!queue.isEmpty()) {
            int cur = queue.poll();
            res.add(cur);
            if (adjList.containsKey(cur)) {
                for (int next : adjList.get(cur)) {
                     queue.offer(next);
                }
            }
        }
        return res;
        
    }
}
public class Solution {
    private void add(HashMap<Integer, List<Integer>> parentVsChild, Set<Integer> res, int kill) {
        res.add(kill);
        List<Integer> children = parentVsChild.get(kill);
        if (children != null) {
            for (Integer val : children) {
                add(parentVsChild, res, val);
            }
        }
    }
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        HashMap<Integer, List<Integer>> parentVsChild = new HashMap<>();

        for (int i = 0; i < ppid.size(); i++) {
            Integer parentId = ppid.get(i);
            if (parentId == 0 && kill == pid.get(i)) {
                return pid;
            }
            List<Integer> children = parentVsChild.get(parentId);
            if (children == null) {
                children = new ArrayList<>();
                parentVsChild.put(parentId, children);
            }
            children.add(pid.get(i));
        }
        Set<Integer> res = new HashSet<>();
        add(parentVsChild, res, kill);
        return new ArrayList<>(res);
    }
}

以上是关于java 582. Kill Process(1st).java的主要内容,如果未能解决你的问题,请参考以下文章

java 582. Kill Process(1st).java

java 582. Kill Process(1st).java

java 582. Kill Process(1st).java

java 582. Kill Process(1st).java

[leetcode-582-Kill Process]

582. Kill Process