zoukankan      html  css  js  c++  java
  • 【python-leetcode141-快慢指针】环形链表

    问题描述:

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

    为了表示给定链表中的环,我们使用整数 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%,那就不是代码的问题了。 

  • 相关阅读:
    设计模式
    包装类
    php 闭包的理解
    is_null empty isset等的判定
    PHP基础一 $this ,static 和 self的区别
    lumen安装踩过得坑
    composer的使用和安装
    使用submine来写c++
    php 和 thinkphp中的常量一览
    路径问题 ./ / ../ 空 的区别
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12337191.html
Copyright © 2011-2022 走看看