leetcode python3 简单题141. Linked List Cycle

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值