HashMap with BFS traverse


  • 0
    Y

    Almost same with other's hashmap solution. Only use BFS to traverse and beat 89%.
    ...

    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        HashMap<Integer, List<Integer>> maps = new HashMap<>();
    
        int nums = pid.size();
        for (int i = 0; i < nums; i++) {
            int p = pid.get(i);
            int pp = ppid.get(i);
    
            if (!maps.containsKey(pp)) {
                List<Integer> list = new LinkedList<Integer>();
                list.add(p);
                maps.put(pp, list);
            } else {
                List<Integer> list = maps.get(pp);
                list.add(p);
            }
        }
    
        List<Integer> result = new LinkedList<Integer>();
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(kill);
        while (!queue.isEmpty()) {
            int id = queue.poll();
            result.add(id);
            List<Integer> list = maps.get(id);
            if (list == null) {
                continue;
            }
            for (Integer d:list) {
                queue.offer(d);
            }
        }
        
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.