[LeetCode] seeking two lists focal --Intersection of Two Linked Lists

Address the topic title

1. problem-solving Italian

Focus solving two of the list, this is not the focal point of intersection of equal value, but after the data required intersection is completely equal.
Implement the java level, it is at the intersection of the object is the same object can be.

ps: I initially did not understand the subject, and then began to compare the value of the node are equal, the example run until failure to know why.

2.-class solution

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA!=null && headB!=null){
            ListNode tempA=headA;
            ListNode tempB=headB;
            while(tempA!=null){
                while(tempB!=null){
                    if(tempA==tempB){
                        return tempA;
                    }    
                    tempB=tempB.next;
                }
                tempB=headB;
                tempA=tempA.next;
            }
        }
        return null;      
    }

Here come through each node by way of two-cycle, if the node is to return to the same object, which is our normal way of thinking.
The following results hit the face: time complexity | space complexity than 5% of the solution.
Hey, or read the title of the problem, the subject of the request time complexity is O (n), the spatial complexity is O (1); it should be a better solution.

3. better solution

First, assume the existence of an intersection, the intersection after the chain length is C, A chain is the length before the intersection a, the length of the list before the intersection B is B;
length A is a + c; length B is b + c

If we let the two sides are equal, that is the length becomes a + b + c, then the last linked list node A is the node prior to the intersection list B, i.e., the next node is an intersection; The last node in the same way a list of B a node is the point of intersection;

In this way, we can traverse only once, you can find the intersection, the maximum length of a + b + c + 1, you can find the intersection;

code show as below:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode l1 = headA, l2 = headB;
    while (l1 != l2) {
        l1 = (l1 == null) ? headB : l1.next;
        l2 = (l2 == null) ? headA : l2.next;
    }
    return l1;
}

Reference: https://cyc2018.github.io/CS-Notes/#/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E9%93%BE%E8%A1 % A8

Guess you like

Origin www.cnblogs.com/paxing/p/11260338.html