Why always Time Limit Exceeded


  • 0
    J
       public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    	if(headA == null || headB == null) {
    		return null;
    	}
    	ListNode head1 = headA;
    	ListNode head2 = headB;
    	int lengthA = getListLength(head1);
    	int lengthB = getListLength(head2);
    	
    	if(head1 != head2){
    		return null;
    	}
    	
    	ListNode longHead = headA;
    	ListNode shortHead = headB;
    	if(lengthB > lengthA) {
    		longHead = headB;
    		shortHead = headA;
    	}
    	int diff = Math.abs(lengthA-lengthB);
    	for(int i = 0; i < diff; i++){
    		longHead = longHead.next;
    	}
    	while(longHead != shortHead){
    		longHead = longHead.next;
    		shortHead = shortHead.next;
    	}
    	return shortHead;
    }
    
    private int getListLength(ListNode head){
    	int length = 1;
    	while(head.next != null) {
    		length++;
    	}
    	return length;
    }

  • 0
    J

    in getListLength, you forget to put 'head = head.next;' so, head always has next.


Log in to reply
 

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