leetcode 582. Kill Process

来源:互联网 发布:美工穿什么衣服 编辑:程序博客网 时间:2024/06/07 19:51
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 = 5Output: [5,10]Explanation:            3         /   \        1     5             /            10Kill 5 will also kill 10.Note:The given kill id is guaranteed to be one of the given PIDs.n >= 1.

主要注意不能超时
最蠢的方法是构建一个队列,一个一个的扩展孩子,一次次的遍历ppid。

一种先遍历一遍ppid,构建一个HashMap, key 为ppid,value为以key为父节点的集合。

public class Solution {    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {        ArrayList<Integer> res = new ArrayList<>();        HashMap<Integer, ArrayList<Integer>> nbMap = new HashMap<>();        for(int i=0; i<ppid.size(); i++){            int p_value = ppid.get(i);            ArrayList<Integer> value = nbMap.getOrDefault(p_value, new ArrayList<>());            if(value.size()==0){                value.add(pid.get(i));                nbMap.put(p_value, value);            }else{                value.add(pid.get(i));            }        }        res.add(kill);        ArrayList<Integer> child = nbMap.getOrDefault(kill, null);        if(child!=null)            addChild(child, res, nbMap);        return res;    }    public void addChild(ArrayList<Integer> child, ArrayList<Integer> res, HashMap<Integer, ArrayList<Integer>> nbMap){        res.addAll(child);        for(int i=0; i< child.size(); i++){                ArrayList<Integer> tp = nbMap.getOrDefault(child.get(i), null);                if(tp!=null){                    addChild(tp, res, nbMap);                }        }    }}

这里一个巧妙的地方是addChild方法。
如果不这样,需要创建一个临时list,把child中每个元素扩展的节点都加进去,这个加入过程可能费时间。不如直接分开做。

原创粉丝点击