leetcode142. 环形链表 II

leetcode142. 环形链表 II

题目

在这里插入图片描述

思路

集合法

  • 将节点存入set,若重复出现则说明是环

快慢指针法

  • 分别定义 fast 和 slow 指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。
  • 初次相遇后,将slow设为头结点,slow和fast这两个指针每次只走一个节点, 当这两个指针相遇的时候就是环形入口的节点。

代码

集合法

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node_set = set()
        current = head
        while current:
            if current in node_set:
                return current
            else:
                node_set.add(current)
                current = current.next
        return None

快慢指针法

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

相关推荐

  1. leetcode142.环形II

    2024-02-15 05:22:03       70 阅读
  2. LeetCode[141] [142] 环形I II

    2024-02-15 05:22:03       68 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-15 05:22:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-15 05:22:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-15 05:22:03       82 阅读
  4. Python语言-面向对象

    2024-02-15 05:22:03       91 阅读

热门阅读

  1. 深入理解WebSocket协议:实现实时通信的利器

    2024-02-15 05:22:03       52 阅读
  2. 双非本科准备秋招(23.1)—— 力扣二叉搜索树

    2024-02-15 05:22:03       59 阅读
  3. v-model原理

    2024-02-15 05:22:03       48 阅读
  4. 数据结构-树

    2024-02-15 05:22:03       45 阅读
  5. 只用cin和cout

    2024-02-15 05:22:03       54 阅读
  6. 多态

    多态

    2024-02-15 05:22:03      46 阅读
  7. Redis缓存击穿

    2024-02-15 05:22:03       53 阅读
  8. 蓝桥杯官网填空题(质数拆分)

    2024-02-15 05:22:03       59 阅读
  9. 虚拟dom

    2024-02-15 05:22:03       53 阅读
  10. centos7 mysql8安装教程

    2024-02-15 05:22:03       40 阅读
  11. vue 封装request请求 多域名访问

    2024-02-15 05:22:03       51 阅读
  12. 限制Unity帧率的方式

    2024-02-15 05:22:03       59 阅读