原题链接:https://leetcode.cn/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
这个题目一开始就用很笨的方法做的
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
lenA, lenB := 0, 0
pA, pB := headA, headB
for pA != nil {
pA = pA.Next
lenA++
}
for pB != nil {
pB = pB.Next
lenB++
}
pA, pB = headA, headB
if lenA > lenB {
sub := lenA - lenB
for sub > 0 {
pA = pA.Next
sub--
}
} else if lenB > lenA {
sub := lenB - lenA
for sub > 0 {
pB = pB.Next
sub--
}
}
for pA != nil {
if pA == pB {
return pA
}
pA = pA.Next
pB = pB.Next
}
return nil
}
但是这个方法就不太好,题解中有两种方法
- 第一种,哈希表
func getIntersectionNode(headA, headB *ListNode) *ListNode {
mpA := make(map[*ListNode]bool)
pA, pB := headA, headB
for pA != nil {
mpA[pA] = true
pA = pA.Next
}
for pB != nil {
if _, ok := mpA[pB]; ok {
return pB
}
pB = pB.Next
}
return nil
}
- 小技巧 – 对的人终会相遇
func getIntersectionNode(headA, headB *ListNode) *ListNode {
pA, pB := headA, headB
for pA != pB {
if pA == nil {
pA = headB
} else {
pA = pA.Next
}
if pB == nil {
pB = headA
} else {
pB = pB.Next
}
}
return pA
}
为啥这么做的话,可以点进题解去看下证明