zoukankan      html  css  js  c++  java
  • 【Leetcode链表】环形链表 II(142)

    题目

    给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

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

    说明:不允许修改给定的链表。

    示例 1:

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

    示例 2:

    输入:head = [1,2], pos = 0
    输出:tail connects to node index 0
    解释:链表中有一个环,其尾部连接到第一个节点。
    

    示例 3:

    输入:head = [1], pos = -1
    输出:no cycle
    解释:链表中没有环。
    

    进阶:
    你是否可以不用额外空间解决此题?

    解答

    两种方法:
    1,用哈希表,依次遍历链表set存储走过的点,遇见重复的就是环入口 ———— 时间复杂度O(n),空间复杂度O(n)
    2,快慢指针,指针在环内相遇的位置到环入口的距离 == 表头到环入口的距离,两者相向而行,相遇位置就是环入口 ———— 时间复杂度O(n²),空间复杂度O(1)

    通过代码如下:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    # 哈希表:时间复杂度O(n),空间复杂度O(n)
    # class Solution:
    #     def detectCycle(self, head: ListNode) -> ListNode:
    #         s = set()
    #         while head:
    #             if head in s:
    #                 return head
    #             s.add(head)
    #             head = head.next
    #         return None
    
    
    # 指针法:时间复杂度O(n²),空间复杂度O(1)
    # 1,快慢双指针找到相遇位置
    # 2,相遇位置到环入口的距离 == 表头到环入口的距离,两者相向而行,相遇位置就是环入口
    class Solution:
        def detectCycle(self, head: ListNode) -> ListNode:
            f = s = h = head  # h记录表头
            while f and f.next:
                s = s.next
                f = f.next.next
                if f == s:  # 相遇了,开始和表头相对走,找环入口
                    p = f
                    while h!=p:
                        h = h.next
                        p = p.next
                    return h
                head = head.next
            return None
    
  • 相关阅读:
    C#实现清理系统内存
    WinForm 程序加管理员权限
    DataGridView 绑定List集合后实现自定义排序
    swfupload提示“错误302”的解决方法
    C# WinForm捕获全局异常
    C# WinForm应用程序降低系统内存占用方法
    清除webBrowser 缓存和Cookie的解决方案
    ThInkPHP加密和解密cookie(登录操作)
    prestashop 首页轮播幻灯片图片修改
    网页内容分享到微信
  • 原文地址:https://www.cnblogs.com/ldy-miss/p/11924376.html
Copyright © 2011-2022 走看看