javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

160. 相交链表

Open Geekhyt opened this issue 4 years ago • 2 comments
trafficstars

原题链接

双指针

  1. 借助双指针分别遍历链表 A 和 B。
  2. 遍历完自己后再将头指针指向另一个链表头部,继续遍历。
  3. 如果存在交点,则一定会相遇。
const getIntersectionNode = function(headA, headB) {
    if (headA === null || headB === null) {
        return null
    }
    let pA = headA, pB = headB
    while (pA !== pB) {
        pA = pA === null ? headB : pA.next
        pB = pB === null ? headA : pB.next
    }
    return pA
}
  • 时间复杂度:O(m + n)
  • 空间复杂度:O(1)

Geekhyt avatar Aug 05 '21 13:08 Geekhyt

if (headA === null || headB === null) {
        return null
    }

这一句应该不用判断的,如果其中一个是null,他们走一遍之后必定是null相等

eavan5 avatar Sep 23 '21 14:09 eavan5

if (headA === null || headB === null) {
        return null
    }

这一句应该不用判断的,如果其中一个是null,他们走一遍之后必定是null相等

需要的,如果其中一个是 null,那么一定不相交,就没有必要“走一遍”咯。

Geekhyt avatar Sep 23 '21 15:09 Geekhyt