leetcode NO.141 环形链表 白痴讲解 腾讯精选练习50

在这里插入图片描述在这里插入图片描述
直接法:
原本想法是用list存里面的链表的表头的数字的,结果发现如果给的链表如果数字有相同的话就会不行,于是还是要存链表才行,这样比较费空间

# 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
        """
        p = head
        rec = []
        count = 0
        while p != None:
            if p in rec:
                return True
            else:
                rec.append(p)
                p = p.next
        return False

用set来优化

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None:
            return False
        
        target = {head}
        #set中记录的是该节点(是一个对象,有独立的内存地址,即使.val一样如果不是同一个位置,那也是不同的,能存在set中)
        head =head.next
        while head:
            if head in target:
                return True
            else:
                target.add(head)
                head = head.next
        return False

第三种就是快慢指针
可以理解成博尔特和你在环形赛道上跑步,博尔特跑步的速度是你的两倍,他跑一步等于你跑两步,这样博尔特迟早能追上你。
如果是一条直线的赛道,博尔特则会先比你到达终点。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast,slow = head,head
        while fast and fast.next:
            fast,slow = fast.next.next,slow.next
            if fast == slow:
                return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值