Share my 21ms solution in C


  • 0
    int i, len, len1 = 0, len2 = 0;
    struct ListNode *temp1 = NULL;
    struct ListNode *temp2 = NULL;
    struct ListNode *headC = (struct ListNode *)malloc(sizeof(struct ListNode));
    
    for(temp1 = headA; temp1 != NULL; temp1 = temp1->next)
    {
        len1++;
    }
    for(temp2 = headB; temp2 != NULL; temp2 = temp2->next)
    {
        len2++;
    }
    
    if(len2 > len1)
    {
        len = len2 - len1;
        temp1 = headB;
        temp2 = headA;
    }
    else
    {
        len = len1 - len2;
        temp1 = headA;
        temp2 = headB;
    }
    
    for(i = 0; i < len; i++)
    {
        temp1 = temp1->next;
    }
    while(temp1 != NULL)
    {
        if(temp1 == temp2)
        {
            headC = temp1;
            return headC;
        }
        temp1 = temp1->next;
        temp2 = temp2->next;
    }
    return NULL;

  • 0
    M
    public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node = null;
    	HashSet<ListNode> setA = new HashSet<ListNode>();
    	while(headA != null){
    		setA.add(headA);
    		headA = headA.next;
    	}
    	while(headB != null){
    		if(setA.contains(headB)){
    			node = headB;
    			break;
    		}
    		else
    			headB = headB.next;
    	}
    	return node;
    }
    

    }


  • 0
    M

    First hash a linkedlist,and another linkedlist to find in that hashtable.It's perfect. 300ms


  • 0
    C

    It's not in O(1) space, though.


  • 0
    M

    Yes,you are right, it O(n) time,but I think it's idea is good,do you ?


Log in to reply
 

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