代码随想录 -- 链表 -- 环形链表II

142. 环形链表 II - 力扣(LeetCode)

思路:

        判断是否有环:定义两个指针 fast 和 slow 都指向 head,fast 每次前进两个节点,slow 每次前进一个节点,这样两个指针移动的差值是1,所以如果有环,fast 和 slow 一定会相遇。

        确定环的入口:指针 index1 指向 head,指针 index2 指向 fast,同时前进,相遇的节点就是环的入口。

class Solution(object):
    def detectCycle(self, head):
        fast = slow = head
        s=f=0
        cycle = 0
        if head==None:return None
        while fast.next and fast.next.next and slow.next:
            fast=fast.next.next
            f+=2
            slow=slow.next
            s+=1
            if slow==fast:
                cycle=1
                break
        if cycle==0:
            return None
        index1=head
        index2=fast
        count=0
        while index1!=index2:
            index1=index1.next
            index2=index2.next
            count+=1
        return index1

题解:

方法一:快慢指针法

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow = head
        fast = head
        
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            # If there is a cycle, the slow and fast pointers will eventually meet
            if slow == fast:
                # Move one of the pointers back to the start of the list
                slow = head
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                return slow
        # If there is no cycle, return None
        return None

方法二:集合法: 

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        visited = set()
        
        while head:
            if head in visited:
                return head
            visited.add(head)
            head = head.next
        
        return None

 知识点

python 集合

        集合(set)是一个无序的不重复元素序列,可以使用大括号 { } 创建集合,元素之间用逗号分隔, 或者也可以使用 set() 函数创建集合。创建一个空集合必须用 set() 

添加元素:s.add( x )

计算集合中元素个数:len( s )

判断元素是否在集合中:x in s

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值