leetcode141 環形鍊錶

2021-09-13 10:13:48 字數 1020 閱讀 5290

給定乙個鍊錶,判斷鍊錶中是否有環。

為了表示給定鍊錶中的環,我們使用整數 pos 來表示鍊錶尾連線到鍊錶中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鍊錶中沒有環。

示例 1:

輸入:head = [3,2,0,-4], pos = 1

輸出:true

解釋:鍊錶中有乙個環,其尾部連線到第二個節點。

示例 2:

輸入:head = [1,2], pos = 0

輸出:true

解釋:鍊錶中有乙個環,其尾部連線到第乙個節點。

示例 3:

輸入:head = [1], pos = -1

輸出:false

解釋:鍊錶中沒有環。

高階:你能用 o(1)(即,常量)記憶體解決此問題嗎?

快慢指標:

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

(object):

defhascycle

(self, head)

:"""

:type head: listnode

:rtype: bool

"""slow, fast = head, head # 快慢指標

while fast and fast.

next

: slow = slow.

next

fast = fast.

next

.next

if slow == fast:

return

true

return

false

leetcode141 環形鍊錶

給定乙個鍊錶,判斷鍊錶中是否有環。高階 你能否不使用額外空間解決此題?思路 剛開始想著讓他迴圈下去,直到和頭結點相同的時候,就返回 true,否則就返回 false,但還是 too young too 實際上還是設定兩個指標,乙個快指標和乙個慢指標,只要是在環裡面,總會相遇的,就可 return t...

LeetCode141 環形鍊錶

題目描述 給定乙個鍊錶,判斷鍊錶中是否有環。高階 你能否不使用額外空間解決此題?演算法描述 1.使用兩個快慢指標遍歷鍊錶。slow每次走一步,fast每次走兩步。fast走到鍊錶尾部無環,slow與fast重疊則有環。2.若鍊錶的起始位置等於環的起始位置 slow走一圈回到起始位置,fast剛好走了...

LeetCode141環形鍊錶

給定乙個鍊錶,判斷鍊錶中是否有環。設定兩個指標,乙個fast乙個slow,遍歷整個列表,若達到表尾時仍未出現指標相等則鍊錶無環。c語言版 definition for singly linked list.struct listnode bool hascycle struct listnode h...