TLE for this question


  • 0
    H

    The code couldnt pass the longest test case for time limit exceeds. I used queue to store neighbors and has a hashmap of old node link to the new node, do anyone have any idea what is wrong with it ?

    public class Solution {
        
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            
            if(node == null)
                return null;
            
            HashMap<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
            Queue<UndirectedGraphNode> queue = new ArrayDeque<UndirectedGraphNode>();
            queue.add(node);
            
    
            while(!queue.isEmpty()){
                
                UndirectedGraphNode curNode = queue.remove();
                UndirectedGraphNode cloneNode;
                
                if(map.get(curNode) == null){
                    
                    cloneNode = new UndirectedGraphNode(node.label);
                    map.put(curNode, cloneNode);
                } else
                    cloneNode = map.get(curNode);
                    
                int length = curNode.neighbors.size();
                for(int i = 0; i < length ; i ++){
                            
                    //get neighbor
                    UndirectedGraphNode neighbor = curNode.neighbors.get(i);
                    
                    if(neighbor != curNode)
                        queue.add(neighbor);
                            
                    if(map.get(neighbor) != null){
                                
                        cloneNode.neighbors.add(map.get(neighbor));
                    }else{
                                
                        UndirectedGraphNode cloneNeighbor = new UndirectedGraphNode(neighbor.label);
                        map.put(neighbor, cloneNeighbor);
                        cloneNode.neighbors.add(cloneNeighbor);
                    }
                }   
    
            }
            
            
            
            UndirectedGraphNode cloneNode = map.get(node);
            
            return cloneNode;
            
        }
    }

Log in to reply
 

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