Python 鏈表中間是否有環 Leetcode No.141
Ps:用英語的不是為了裝哈,主要是為了鍛煉一下英語閱讀,畢竟想往上走的話,讀源碼,讀文檔,讀國外論文都是必經之路。那么英語能力必不可少,希望你們也可以想我一樣。
主要意思就是判斷鏈表中是否有環。
思路也很簡單:一個是用set存,發現他數量不加了那不就代表有環了嘛。
第二種方式非常的巧妙,用一個快指針和一個慢指針,就等于是一個龜兔賽跑,兔子是快指針,龜是慢指針,只要是個鏈表沒有環,兔子肯定跑的快,這種方法優點是空間復雜度為O(1)
#第一種方法,借用了set的數據結構
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class
Solution
(
object
)
:
def
hasCycle
(
self
,
head
)
:
"""
:type head: ListNode
:rtype: bool
"""
a
=
set
(
)
p
=
head
while
p
and
p
.
next
:
lenth1
=
len
(
a
)
a
.
add
(
id
(
p
)
)
lenth2
=
len
(
a
)
if
lenth2
==
lenth1
:
return
True
p
=
p
.
next
return
False
#第二種方法
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class
Solution
(
object
)
:
def
hasCycle
(
self
,
head
)
:
"""
:type head: ListNode
:rtype: bool
"""
fast
=
slow
=
head
while
slow
and
fast
and
fast
.
next
:
slow
=
slow
.
next
fast
=
fast
.
next
.
next
if
slow
is
fast
:
return
True
return
False
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
