Why this solution is throwing TLE???


  • 0
    L
    public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null)
            return null;
        
        UndirectedGraphNode copyNode = new UndirectedGraphNode(node.label);
        
        //object insert into map, O(logN)
        HashMap<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        map.put(node, copyNode);
        
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        queue.offer(node);
        while (!queue.isEmpty()){
        	UndirectedGraphNode tempNode = queue.poll();
        	UndirectedGraphNode copytempNode = map.get(tempNode);
        	ArrayList<UndirectedGraphNode> copyNeighbors = new ArrayList<UndirectedGraphNode>();
        	for (UndirectedGraphNode i : tempNode.neighbors){
        		if (!map.containsKey(i)){
            		UndirectedGraphNode copy = new UndirectedGraphNode(tempNode.label);
            		map.put(i, copy);
            		copyNeighbors.add(copy);
        		}
        		if (i != tempNode)
        			queue.offer(i);
        	}
        	copytempNode.neighbors = copyNeighbors;
        }
        return copyNode;
    }
    

    }


Log in to reply
 

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