KL160相交链表
方法一:
红色是相交部分,找到长度差的地方,两个指针同时向后找即可。
时间复杂度:O(m+n+n)
空间复杂度:O(1)
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode p1 = headA;
ListNode p2 = headB;
int n1 = 1, n2 = 1;
while (p1 != null) {
p1 = p1.next;
n1++;
}
while (p2 != null) {
p2 = p2.next;
n2++;
}
int n3 = Math.abs(n1 - n2);
p1 = headA;
p2 = headB;
if (n1 >= n2) {
for (int i = 0; i < n3; i++) {
p1 = p1.next;
}
while (p1 != null) {
if (p1 == p2) {
return p1;
}
p1 = p1.next;
p2 = p2.next;
}
return null;
} else {
for (int i = 0; i < n3; i++) {
p2 = p2.next;
}
while (p1 != null) {
if (p1 == p2) {
return p1;
}
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}
}
方法二:
方法1就是类似方法2,只不过不用提前移动指针,只需要交替遍历一次就可以保证两个数组步调一致了
指针1开始走的:a+c+b
指针2开始走的:b+c+a
他们走的次数一样,而且都到了红色部分。如果相交,已经找到了。
时间复杂度:O(m+n) 比方法一稍微快了一点
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}