O(n^2) slow but easy to understand Java solution


  • 0
    W

    Use the kill as started point and then, check if the ppid is included in the toKill set, get the index of that ppid and add the corresponding pid into the toKill set. Keep doing that until the toKill size no longer changes. In worst case, it will be O(n^2)

    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
    	Set<Integer> toKill = new HashSet<>();
    	toKill.add(kill);
    	int size = 0;
    	while (size == toKill.size()) {
    		size = toKill.size();
    		for (int i = 0; i < ppid.size(); i++) {
    			if (toKill.contains(ppid.get(i))) {
    				toKill.add(pid.get(i));
    			}
    		}
    	}
    	List<Integer> re = new ArrayList<Integer>();
    	Iterator<Integer> ite = toKill.iterator();
    	while (ite.hasNext()) {
    		re.add(ite.next());
    	}
    	return re;
    }
    

Log in to reply
 

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