141. 环形链表

本文介绍了一种高效检测链表中是否存在环的方法,通过三种不同的Python实现方式对比,包括使用额外标记、集合记录节点ID及双指针技术,旨在帮助读者理解并掌握环形链表的检测原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

141. 环形链表

题意

判断链表中是否有环;

提升:

空间复杂度为O(1)

解题思路

  • 标记链表结点是否已经访问过(通过Python的属性很容易实现);

  • 使用集合记录下访问过的结点的id;

  • 慢结点每次走一步,快结点每次走两步,如果存在环的话两者肯定会相逢(考点!!);

考察的就是第三种方法,其余的方法都是相对投机取巧的方式来实现的;

实现

class Solution(object):
   def hasCycle(self, head):
       """
      执行用时 : 76 ms, 在Linked List Cycle的Python提交中击败了9.34% 的用户
内存消耗 : 18.2 MB, 在Linked List Cycle的Python提交中击败了9.07% 的用户
      :type head: ListNode
      :rtype: bool
      """
       tmp = head
       while tmp:
           if getattr(tmp, "is_visited", False):
               return True
           tmp.is_visited = True
           tmp = tmp.next
       return False
     
   def hasCycle(self, head):
       """
      执行用时 : 64 ms, 在Linked List Cycle的Python提交中击败了14.15% 的用户
内存消耗 : 18.7 MB, 在Linked List Cycle的Python提交中击败了5.29% 的用户
      :type head: ListNode
      :rtype: bool
      """
       tmp = head
       visited_set = set()
       while tmp:
           tmp_id = id(tmp)
           if tmp_id in visited_set:
               return True

           visited_set.add(id(tmp))
           tmp = tmp.next
       return False
     
   def hasCycle(self, head):
       """
      执行用时 : 64 ms, 在Linked List Cycle的Python提交中击败了14.15% 的用户
内存消耗 : 18.1 MB, 在Linked List Cycle的Python提交中击败了9.32% 的用户
      :type head: ListNode
      :rtype: bool
      """
       if not head or not head.next:
           return False

       tmp = head
       next_tmp = head.next
       while next_tmp and next_tmp.next:
           if tmp == next_tmp:
               return True
           tmp = tmp.next
           next_tmp = next_tmp.next.next
       return False

转载于:https://www.cnblogs.com/George1994/p/10591759.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值