Java BFS beats 100%


  • 0
    M

    We can actually do BFS without using queue or stack in while loop.
    Saves both time and space.

        public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
            HashMap<Integer,List<Integer>> map=new HashMap<Integer,List<Integer>>();
            List<Integer> result=new ArrayList<Integer>();
            int index=0;
            for(int i=0;i<ppid.size();i++){
                if(!map.containsKey(ppid.get(i))) map.put(ppid.get(i),new ArrayList<Integer>());
                map.get(ppid.get(i)).add(pid.get(i));
            }
            result.add(kill);
            while(index<result.size()){
                int tmp=result.size();
                while(index<tmp){
                    if(map.containsKey(result.get(index))){
                        result.addAll(map.get(result.get(index)));
                    }
                    index++;
                }
            }
            return result;
            
        }
    

Log in to reply
 

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