BiruLyu
7/3/2017 - 3:25 AM

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);
    }
}