160 相交鍊錶

2021-09-28 11:34:03 字數 2481 閱讀 7546

編寫乙個程式,找到兩個單鏈表相交的起始節點。

如下面的兩個鍊錶:

在節點 c1 開始相交。

示例 1:

輸入:intersectval = 8, lista = [4,1,8,4,5], listb = [5,0,1,8,4,5], skipa = 2, skipb = 3

輸出:reference of the node with value = 8

輸入解釋:相交節點的值為 8 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,鍊錶 a 為 [4,1,8,4,5],鍊錶 b 為 [5,0,1,8,4,5]。在 a 中,相交節點前有 2 個節點;在 b 中,相交節點前有 3 個節點。

示例 2:

輸入:intersectval = 2, lista = [0,9,1,2,4], listb = [3,2,4], skipa = 3, skipb = 1

輸出:reference of the node with value = 2

輸入解釋:相交節點的值為 2 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,鍊錶 a 為 [0,9,1,2,4],鍊錶 b 為 [3,2,4]。在 a 中,相交節點前有 3 個節點;在 b 中,相交節點前有 1 個節點。

示例 3:

輸入:intersectval = 0, lista = [2,6,4], listb = [1,5], skipa = 3, skipb = 2

輸出:null

輸入解釋:從各自的表頭開始算起,鍊錶 a 為 [2,6,4],鍊錶 b 為 [1,5]。由於這兩個鍊錶不相交,所以 intersectval 必須為 0,而 skipa 和 skipb 可以是任意值。

解釋:這兩個鍊錶不相交,因此返回 null。

注意:如果兩個鍊錶沒有交點,返回 null.

在返回結果後,兩個鍊錶仍須保持原有的結構。

可假定整個鍊錶結構中沒有迴圈。

程式盡量滿足 o(n) 時間複雜度,且僅用 o(1) 記憶體。

思路:雙指標法

建立兩個指標 papa 和 pbpb,分別初始化為鍊錶 a 和 b 的頭結點。然後讓它們向後逐結點遍歷。

當 papa 到達鍊錶的尾部時,將它重定位到鍊錶 b 的頭結點 (你沒看錯,就是鍊錶 b); 類似的,當 pbpb 到達鍊錶的尾部時,將它重定位到鍊錶 a 的頭結點。

若在某一時刻 papa 和 pbpb 相遇,則 papa/pbpb 為相交結點。

想弄清楚為什麼這樣可行, 可以考慮以下兩個鍊錶: a= 和 b=,相交於結點 9。 由於 b.length (=4) < a.length (=6),pbpb 比 papa 少經過 22 個結點,會先到達尾部。將 pbpb 重定向到 a 的頭結點,papa 重定向到 b 的頭結點後,pbpb 要比 papa 多走 2 個結點。因此,它們會同時到達交點。

如果兩個鍊錶存在相交,它們末尾的結點必然相同。因此當 papa/pbpb 到達鍊錶結尾時,記錄下鍊錶 a/b 對應的元素。若最後元素不相同,則兩個鍊錶不相交。

複雜度分析

時間複雜度 : o(m+n)

空間複雜度 : o(1)

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class solution(object):

def getintersectionnode(self, heada, headb):

""":type head1, head1: listnode

:rtype: listnode

"""p,q = heada,headb

while p!=q:

p = p.next if p else headb

q = q.next if q else heada

return q

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class solution(object):

def getintersectionnode(self, heada, headb):

hasha = {}

while heada:

hasha[heada] = 1

heada = heada.next

while headb:

if hasha.get(headb) is not none:

return headb

headb = headb.next

160 相交鍊錶

編寫乙個程式,找到兩個單鏈表相交的起始節點。如下面的兩個鍊錶 在節點 c1 開始相交。示例 1 輸入 intersectval 8,lista 4,1,8,4,5 listb 5,0,1,8,4,5 skipa 2,skipb 3 輸出 reference of the node with valu...

160 相交鍊錶

題目描述 題目問題和難點 1.是找相交的那個節點,而不是值相等的節點。示例中1的值相同但不是相交的節點 2.此題目不考慮有環的鍊錶所以思路很簡單。public static listnode getintersectionnode listnode heada,listnode headb 1.獲取...

160相交鍊錶

題目描述 編寫乙個程式,找到兩個單鏈表相交的起始節點。沒有就返回null。注意 題解思路 從a鍊錶第乙個元素開始,去遍歷b鍊錶,找到乙個相同元素後,同步遍歷a和b鍊錶,所有元素相同,即兩個鍊錶為相交鍊錶,並返回同步遍歷的起始節點。struct listnode getintersectionnode...