Offer to prove safety of the programming problem (Java implementation) - The first two lists of common node

Subject description:

Two input lists, find their first common node.

A thought:

 Let A length of a + c, the length B is b + c, where c is the common length of the tail portion, it can be seen a + c + b = b + c + a.

When the pointer to access the list A list of access tail, so that access the list B to restart from the head of the list B; likewise, when the pointer to access the list B to access the list of the tail, it once more from the head of the list A He began to access the list A. This would control the pointers A and B access the list simultaneously access to the intersection.

achieve:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        // 很厉害的解法
        ListNode l1 = pHead1, l2 = pHead2;
        while (l1 != l2) {
            l1 = (l1 == null) ? pHead2 : l1.next;
            l2 = (l2 == null) ? pHead1 : l2.next;
        }
        return l1;
        
    }
}

Running time: 19ms

Take up memory: 9528k

Thinking two:

Violence double loop iteration

achieve:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        // 暴力解法
        ListNode tmp1 = pHead1;
        ListNode tmp2 = pHead2;
        while(tmp1 != null){
            while(tmp2 != null){
                if(tmp1 == tmp2)
                    return tmp1;
                tmp2 = tmp2.next;
            }
            tmp2 = pHead2;
            tmp1 = tmp1.next;
        }
        return null;
    }
}

Running time: 21ms

Take up memory: 9680k

Ideas Reference: https://www.nowcoder.com/discuss/198840

Guess you like

Origin www.cnblogs.com/MWCloud/p/11323173.html