KL160相交链表
方法一:
红色是相交部分,找到长度差的地方,两个指针同时向后找即可。
时间复杂度:O(m+n+n)
空间复杂度:O(1)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5tBJNSiP-1651203153209)(D:\学习\截图\image-20220429110142890.png)]](https://i-blog.csdnimg.cn/blog_migrate/0e66049a02561c3096cf4097de1e3269.png)
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,只不过不用提前移动指针,只需要交替遍历一次就可以保证两个数组步调一致了
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xDsLRjdR-1651203153210)(D:\学习\截图\image-20220429111852712.png)]](https://i-blog.csdnimg.cn/blog_migrate/7434be886dae095d2b335160a570c216.png)
指针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;
}
}
本文探讨了两种优化方法解决相交链表问题:一种通过预计算长度差,然后同步移动指针;另一种仅需交替遍历,降低到O(m+n)的时间复杂度。两种方法对比,适用于不同场景并提升效率。
7万+

被折叠的 条评论
为什么被折叠?



