题目描述

题解
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode cur = headA;
while (cur != null) {
set.add(cur);
cur = cur.next;
}
cur = headB;
while (cur != null) {
if (!set.add(cur))
return cur;
cur = cur.next;
}
return null;
}
}
// 双指针
// 本题和【剑指offer】52. 两个链表的第一个公共结点 一模一样
// 执行用时:2 ms, 在所有 Java 提交中击败了27.73%的用户
// 内存消耗:41.1 MB, 在所有 Java 提交中击败了73.96%的用户
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null
ListNode a = headA
ListNode b = headB
while (a != null || b != null) {
if (a == null)
a = headB
if (b == null)
b = headA
if (a != null && b != null && a == b)
return a
a = a.next
b = b.next
}
return null
}
}
// 改进一下实现,把while的执行和终止逻辑反一下:
// 执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:40.9 MB, 在所有 Java 提交中击败了93.35%的用户
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null
}
ListNode a = headA
ListNode b = headB
while (a != b) {
if (a == null)
a = headB
else
a = a.next
if (b == null)
b = headA
else
b = b.next
}
return a
}
}
// 简化一下:
// 执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:41.1 M, 在所有 Java 提交中击败了84.56%的用户s
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null
}
ListNode a = headA
ListNode b = headB
while (a != b) {
a = (a == null) ? headB : a.next
b = (b == null) ? headA : b.next
}
return a
}
}