Problem: 160. 相交链表
文章目录
- 思路 & 解题方法
- 复杂度
- 哈希
- 技巧
思路 & 解题方法
可以用hash做,也可以做一个技巧。
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
哈希
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:hashTable = collections.defaultdict(int)while headA:hashTable[headA] += 1headA = headA.nextwhile headB:if headB in hashTable:return headBheadB = headB.nextreturn None
技巧
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:A, B = headA, headBwhile A != B:A = A.next if A else headBB = B.next if B else headAreturn A