原题链接:https://leetcode.com/problems/contains-duplicate-iii/
这道题目是easy题,所以会有可能出现在电面里面。思路也很简单,设置2个指针分别指向2个链表,如果链表长度不相等,假设2个链表相差k个节点,则我们让长度长的那个链表对应的指针先走前进k个节点,然后两个指针一起走,直走到2个指针指向相同的节点为止。时间复杂度是O(n)
代码如下:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
int lenA = 0;
ListNode pA = headA;
int lenB = 0;
ListNode pB = headB;
while(pA!=null)
{
lenA++;
pA = pA.next;
}
while(pB!=null)
{
lenB++;
pB = pB.next;
}
int diff = Math.abs(lenA-lenB);
pA = headA;
pB = headB;
if(lenA>lenB)
{
while(diff>0 && pA!=null)
{
pA = pA.next;
diff--;
}
}
else if(lenA<lenB)
{
while(diff>0 && pB!=null)
{
pB = pB.next;
diff--;
}
}
while(pA!=null && pB!=null)
{
if(pA == pB)
return pA;
pA = pA.next;
pB = pB.next;
}
return null;
}