LeetCode 141 環形鍊錶

2021-09-29 13:18:02 字數 1117 閱讀 3437

做法有兩種,第一種,每次遍歷過乙個節點就用雜湊表記錄一下,如果遍歷的點已經被記錄在雜湊變中,返回true,如果whle head 退出迴圈,說明沒有環,返回false

第二種, 使用快慢指標,快指標走兩步,慢指標走一步。如果兩個指標相遇了,就返回true。如果快指標遇到了none,就返回false.

class

solution

:def

hascycle

(self, head: listnode)

->

bool:if

not head:

return

false

dic =

while head:

tmp = dic.get(head,

none

)if tmp:

return

true

else

: dic[head]=1

head = head.

next

return

false

class

solution

:def

hascycle

(self, head: listnode)

->

bool:if

not head:

return

false

p = head

q = head.

next

while p != q:

if q==

none

:return

false

p = p.

next

if q.

next

: q = q.

next

.next

else

:return

false

return

true

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...