您好,登錄后才能下訂單哦!
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle-ii
目前考慮到兩種解法,但都需要輔助空間, 第一種 O(n) 第二種 O(1)
將走過的節(jié)點都記錄在字典中,通過查詢字典的key值是否存在來確定是否有環(huán)
時間復(fù)雜度為 O(n) , 空間復(fù)雜度為 O(n)
代碼如下:
# -*- coding: utf-8 -*-
# @Author : xaohuihui
# @Time : 19-12-9
# @File : detect_cycled_ii.py
# Software : study
"""
環(huán)形鏈表ii
"""
class ListNode:
def __init__(self, x):
self.x = x
self.next = None
# Number.1
def has_cycle(head: ListNode) -> ListNode:
result = None
if head and head.next:
set_node = set()
while head:
if head in set_node:
result = head
break
set_node.add(head)
head = head.next
return result
if __name__ == '__main__':
# head=[3,2,0,4] pos= 1
node1 = ListNode(3)
node2 = ListNode(2)
node3 = ListNode(0)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node2
result_node = has_cycle(node1)
if result_node:
start = node1
i = 0
while start:
if result_node == start:
print(f"tail connects to node index {i}")
break
i += 1
start = start.next
else:
print("no cycle")
輸出如下:
tail connects to node index 1
使用快慢指針,快指針每次走兩步,慢指針每次走一步。
如果單鏈表中有環(huán),快慢指針肯定會相遇,如圖a.所示,在相遇后,將快指針指向開始位置,結(jié)束第一次循環(huán)。
第二次循環(huán),將快指針變?yōu)闆]次走一步,慢指針每次走一步,如圖b.所示,如果再次相遇,該點就為環(huán)點
時間復(fù)雜度為 O(n) , 空間復(fù)雜度為 O(1)
特別注意: 若環(huán)點就在起始節(jié)點,第一次快慢指針相遇一定在環(huán)點 ,則fast和slow此時都指向起始節(jié)點,則第二次循環(huán)不必執(zhí)行,如圖c.所示
圖a.
圖b.
圖c.
代碼如下:
# -*- coding: utf-8 -*-
# @Author : xaohuihui
# @Time : 19-12-9
# @File : detect_cycled_ii.py
# Software : study
"""
環(huán)形鏈表ii
"""
class ListNode:
def __init__(self, x):
self.x = x
self.next = None
# NUmber.2
def has_cycle(head: ListNode) -> ListNode:
result = None
if head and head.next:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
fast = head
break
else:
return result
while fast != slow:
fast = fast.next
slow = slow.next
result = fast
return result
if __name__ == '__main__':
# head=[3,2,0,4] pos= 0
node1 = ListNode(3)
node2 = ListNode(2)
node3 = ListNode(0)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node1
result_node = has_cycle(node1)
if result_node:
start = node1
i = 0
while start:
if result_node == start:
print(f"tail connects to node index {i}")
break
i += 1
start = start.next
else:
print("no cycle")
輸出結(jié)果
tail connects to node index 0
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。