1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第一百四十一题
(1)题目
英文:
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
中文:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
(2)解法
① 一个一个地试探
(耗时:1116ms,内存:16.6M)
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head:
return head
m = []
while head:
if head in m:
return True
m.append(head)
head = head.next
return False
② 双指针
(耗时:76ms,内存:16.8M)
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head:
return head
slow = head
quick = head
while quick and slow:
slow = slow.next
if quick.next:
quick = quick.next.next
else:
return False
if quick is slow:
return True
return False