142. 环形链表 II(Python3)

Problem: 142. 环形链表 II

思路

哈希表+单指针

  1. 链表本身读写困难,因此通过遍历先存入散列表;

  2. 在循环中判断是否有环,并返回环的入口节点。

快慢指针

参考:

  1. 第一次相遇慢指针未走过一个环长;

  2. 第二次相遇一定发生在环的入口处。

Code

哈希表+单指针

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        
        visited = set() # 初始化散列表
        temp = head # 指针指向head

        while temp: # 循环遍历进行判断与存储
            if temp in visited: # 若访问过,则返回节点(入环口节点)
                return temp
            
            visited.add(temp) # 添加节点进入散列表
            temp = temp.next # 移动指针

        return None # 没有访问过,则返回 None

快慢指针1 参考灵神

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        
        slow = fast = head # 初始化双指针

        while fast and fast.next: # 判断有环的关键条件
            
            slow = slow.next    # 慢指针
            fast = fast.next.next   # 快指针

            if fast is slow:    # 快慢指针在环中相遇

                while head is not slow: # 快慢指针相遇后移动慢指针和头部指针
                    head = head.next    
                    slow = slow.next
                
                return slow # 头部指针和慢指针必然在环入口处相遇
            
        return None

快慢指针2 参考K神

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        
        slow = fast = head # 初始化双指针

        while True:
            if not (fast and fast.next): return None # 无环
            slow, fast = slow.next, fast.next.next
            if slow is fast: break  # 环中第一次相遇

        fast = head # 重新指向head
        while slow is not fast: # 环入口处第二次相遇
            slow, fast = slow.next, fast.next
        
        return slow

相关推荐

  1. 142. 环形 II(Python3

    2024-01-24 20:02:01       40 阅读
  2. lc142.环形

    2024-01-24 20:02:01       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-24 20:02:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-24 20:02:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-24 20:02:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-24 20:02:01       20 阅读

热门阅读

  1. openssl3.2/test/certs - 025 - client intermediate ca: cca-cert

    2024-01-24 20:02:01       33 阅读
  2. 一次查找某些后缀的文件

    2024-01-24 20:02:01       29 阅读
  3. GDB调试crashdump

    2024-01-24 20:02:01       43 阅读
  4. 1.20号网络

    2024-01-24 20:02:01       32 阅读
  5. 民安智库-医院职工满意度调查报告如何撰写

    2024-01-24 20:02:01       28 阅读
  6. MongoDB基本常用命令(一)

    2024-01-24 20:02:01       34 阅读
  7. Scikit-Learn 中级教程——学习曲线

    2024-01-24 20:02:01       37 阅读
  8. Scikit-Learn 中级教程——特征缩放

    2024-01-24 20:02:01       30 阅读
  9. 【MySQL】Char与VarChar详解

    2024-01-24 20:02:01       38 阅读