首页 > 编程语言 > 详细

【python-leetcode141-快慢指针】环形链表

时间:2020-02-20 21:40:00      阅读:74      评论:0      收藏:0      [点我收藏+]

问题描述:

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

核心思想:两个指针,一个走得慢,一个走得快,如果是有环的话,这两个指针迟早会相遇,否则快指针走到头了,则没有环。

这里有两种写法,第一种:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if head == None or head.next == None:
            return False
        slow = head
        fast = head.next
        while slow != fast:
            if fast == None or fast.next == None:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

结果:

技术分享图片

第二种方式:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if head == None or head.next == None:
            return False
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

技术分享图片

效率都好低,去跑了下leetcode排名第一的python算法,也是7.78%,那就不是代码的问题了。 

 

【python-leetcode141-快慢指针】环形链表

原文:https://www.cnblogs.com/xiximayou/p/12337191.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!