Problem: 160. 相交链表


文章目录

  • 思路 & 解题方法
  • 复杂度
  • 哈希
  • 技巧


思路 & 解题方法

可以用hash做,也可以做一个技巧。

复杂度

时间复杂度:

添加时间复杂度, 示例: 相交链表【哈希】【双指针】_链表

空间复杂度:

添加空间复杂度, 示例: 相交链表【哈希】【双指针】_链表

哈希

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        hashTable = collections.defaultdict(int)
        while headA:
            hashTable[headA] += 1
            headA = headA.next
        while headB:
            if headB in hashTable:
                return headB
            headB = headB.next
        return None

技巧

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        A, B = headA, headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A