[leetcode] 142.环形链表2
生活随笔
收集整理的這篇文章主要介紹了
[leetcode] 142.环形链表2
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)鏈表,返回鏈表開(kāi)始入環(huán)的第一個(gè)節(jié)點(diǎn)。?如果鏈表無(wú)環(huán),則返回?null。
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來(lái)表示鏈表尾連接到鏈表中的位置(索引從 0 開(kāi)始)。 如果 pos 是 -1,則在該鏈表中沒(méi)有環(huán)。注意,pos 僅僅是用于標(biāo)識(shí)環(huán)的情況,并不會(huì)作為參數(shù)傳遞到函數(shù)中。
說(shuō)明:不允許修改給定的鏈表。
進(jìn)階:
- 你是否可以使用?O(1)?空間解決此題?
示例 1:
輸入:head = [3,2,0,-4], pos = 1 輸出:返回索引為 1 的鏈表節(jié)點(diǎn) 解釋:鏈表中有一個(gè)環(huán),其尾部連接到第二個(gè)節(jié)點(diǎn)。示例?2:
輸入:head = [1,2], pos = 0 輸出:返回索引為 0 的鏈表節(jié)點(diǎn) 解釋:鏈表中有一個(gè)環(huán),其尾部連接到第一個(gè)節(jié)點(diǎn)。示例 3:
輸入:head = [1], pos = -1 輸出:返回 null 解釋:鏈表中沒(méi)有環(huán)。提示:
- 鏈表中節(jié)點(diǎn)的數(shù)目范圍在范圍?[0, 104]?內(nèi)
- -105?<= Node.val <= 105
- pos?的值為?-1?或者鏈表中的一個(gè)有效索引
1.暴力解法
class Solution:def detectCycle(self, head: ListNode) -> ListNode:visited = set()curr = headwhile curr != None:if curr in visited:return currelse:visited.add(curr)curr = curr.next2.快慢指針
class Solution:def detectCycle(self,head:ListNode)->ListNode:fast = headslow = headwhile fast != None and fast.next != None:fast = fast.next.nextslow = slow.nextif fast==slow:breakif fast ==None or fast.next ==None:return Nonecur=headwhile cur != slow:cur = cur.nextslow = slow.nextreturn cur總結(jié)
以上是生活随笔為你收集整理的[leetcode] 142.环形链表2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [leetcode] 141.环形链表
- 下一篇: [leetcode] 160.相交链表