自己写的暴力解法,复杂度O(n2)
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode h1 = headA;
ListNode h2 = headB;
while (h1 != h2){
while (h1 != null){
if (h1 == h2) return h1;
h1 = h1.next;
}
if (h2.next == null) return null;
h2 = h2.next;
h1 = headA;
}
return h1;
}
简洁写法:
快慢指针,浪漫相遇
思想来源:
https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/solution/shuang-zhi-zhen-fa-lang-man-xiang-yu-by-ml-zimingm/
代码来源:
https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/comments/
代码:
针对等长不相交的特例,依然是适用的。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//拷贝好头结点
ListNode h1 = headA;
ListNode h2 = headB;
while (h1 != h2){
h1 = h1 == null ? headB : h1.next;
h2 = h2 == null ? headA : h2.next;
}
return h1;
}