LeetCode-Notes
  • Introduction
  • Records of Practice
  • 关于Github 不支持密码问题
  • 面试题
    • 搜索广告
    • 多模态大模型
    • 刷题记录
  • 算法代码实现
  • Python
    • Python 笔记
  • Spark
    • PySpark
    • Spark Issues
    • Spark调优笔记
  • FeatureEngineering
    • Feature Cleaning
    • Feature Selection
    • Feature Transformation
    • Feature Crossing
  • Recommendation Algorithm
    • Recall-and-PreRank
      • Non-Negative Matrix Fatorization(NMF)
      • Fatorization Machine(FM)
      • User-base/Item-base实现
      • 多路召回实现
    • Ranking
      • NeuralFM
      • DeepFM
      • Deep&Cross network (DCN)
    • DeepLearning-Basic
      • Attention
      • Dropout
      • Batch Norm
  • Machine Learning
    • XGBoost
    • Cross Entropy Loss
    • Other models
  • Graph Neural Network
    • GNN-1-Basic
  • Big Data
    • Reservoir Sampling
  • SQL
    • SQL and PySpark functions
    • Query Film Infomation
    • Create, Insert and Alter Actor Table
    • Manage Employment Data
    • Manage Employment Data -2
  • DataStructure
    • Searching
      • Find power
      • 2 Sum All Pair II
      • Two Sum
      • Search in Rotate Array
      • Search In Shifted Sorted Array II
      • Search in 2D array
      • Three Sum with duplicated values
      • Median of Two Sorted Arrays
    • Array
      • Longest Consecutive Subarray
      • Merge Two Array in-place
      • Trapping water
      • Rotate matrix
    • Sorting
      • Merge intervals
      • 排序
      • 最小的k个数
      • Find TopK largest- QuickSelect快速选择 method
      • MergeSort Linkedlist
      • 第K大元素
    • LinkedList
      • Reverse LinkedList I
      • Reverse K-group linked list
      • Detect Start of Cycle
      • HasCycle
      • DetectCycle II
      • 链表的共同节点
      • 链表中倒数第k个节点
      • 删除链表倒数第k个节点
      • 合并两个链表
      • 在排序数组中查找元素的第一个和最后一个位置
      • 删除链表里面重复的元素-1
    • Tree
      • Find Tree height (general iteration method)
      • Check BST and Check CompleteTree
      • ZigZag Order traversal
      • Binary Tree diameter I
      • Maximum Path Sum Binary Tree
      • Maximum Path Sum Binary Tree II
      • Binary Tree Path Sum To Target III
      • Tree diameter 树的直径II
      • Tree ReConstruction
      • Check if B is Subtree of A
      • The Kth smallest in Binary Search Tree
      • 打印Tree的右视图
      • 二叉搜索树的后序遍历序列
      • 重建二叉树
      • 判断二叉树是否对称
      • Path Sum to Target in Binary Tree
      • Tree-PreOrder-InOrder-PostOrder
    • Heap&Queue
      • Top-K smallest
      • 滑动窗口最大值
      • Find the K-Largest
    • 合并k个已排序的链表
    • String
      • Reverse String
      • 最长不含重复字符的子字符串
      • 最长回文串
      • 最长回文子序列-DP
    • DFS/BFS
      • Number of island
      • Number of Provinces
      • All Permutations of Subsets without duplication
      • All Permutations of Subsets with duplication
      • Combinations Of Coins
      • All Subset I (without fixing size of subset, without order, without duplication)
      • All Subset of K size without duplication II
      • All Subset of K size III (with duplication without considering order)
      • All Permutation II (with duplication and consider order)
      • Factor Combination-质数分解
    • DynamicProgramming
      • DP-解题过程
      • Find Continuous Sequence Sum to Target
      • 1800. Maximum Ascending Subarray Sum
      • NC91 最长上升子序列
      • 查找string的编码方式个数
      • Maximum Product
      • Longest Common Substring
      • Longest Common Substring-II
      • minEditCost
      • Backpack I
      • Array Hopper I
      • Minimum distance between strings
      • 最大正方形
  • Big Data Algorithms
    • Big Data Processing Algorithms
      • Reservior Sampling
      • Shuffle
      • MapReduce
      • Bloom Filter
      • BitMap
      • Heap For Big Data
Powered by GitBook
On this page

Was this helpful?

  1. DataStructure
  2. LinkedList

DetectCycle II

LinkedList; Easy

PreviousHasCycleNext链表的共同节点

Last updated 4 years ago

Was this helpful?

1. Link

2. 题目

142. 环形链表 II

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

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

进阶:

你是否可以使用 O(1) 空间解决此题?

示例 1:

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

3. 思路

  1. 用快慢指针的方法

  2. 先用slow, fast pointer 把linkedlist遍历,fast pointer遍历两步,slow pointer遍历一步。假设 X = head 到 cycle第一个点的距离, Y=slow fast pointer相遇的点到cycle第一个点的距离, C= 1个cycle展开后的长度。 那么 head到相遇点(slow)的距离 = X + m * C +Y. head 到fast所在的相遇点的距离 = X + n * C + Y = 2*( X + m * C +Y)。 当这个等式的解为整数时,那么就是slow和fast会相遇,即有loop

  3. 在找到相遇点后,用2个slow pointers, slow1, slow2 分别从head和相遇点出发。当他们再次相遇时,新的相遇点就是cycle的第一个点。

  4. 这是因为head到fast和slow的相遇点的距离 = X + m*C +Y, 而 slow所在的相遇点到fast所在的相遇点距离 = Z + m*C +Y。 而事实上Z就是 相遇点到cycle第一个点的距离, Z=X。 当 slow1, slow2同时向前移动,他们的相遇点就是经过距离Z后的第一个点,即环的入口点

  5. Time Complexity: O(n+k), n=slow和fast相遇点到head的距离, k=head 到环入口的距离。 Space Complexity: O(1)

  6. 例子:

带cycle的linked list展开之后的形式:

1->2 -> 3 ->4 (slow) ->5 ->3->4 (fast)->5 ->3->4->5....

这里的环是3, 4, 5 所以 X= 2, C=3, fast 和slow的相遇点是4 而环的入口是3,所以Y =1。 那么slow1, slow2分别从1 和4(slow)开始前进, X=Z = 2。 当两个pointer到3时就相遇,即环的入口

4. Coding

# 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:
        # input: head of linked list
        # output: entry of the loop
        # idea:
        #   1. check if there is a loop. If so, find the node that slow pt meet fast pt
        #   X: distance from head to entry of loop, Y distance from entry of loop to meeting point
        #   C = lenght of cycle
        #   then we know that distance from slow to the head = X+ m*C+y
        #   distance from fast to the head = X+ n*C+y
        #   Then we have 2*(X+ m*C+y) =  X+ n*C+y. When it has solution, there is a loop
        #
        #   2. use two slow pointers start from head and the meeting point
        #     distance from head to meeting point = X+ m*C+y
        #     distance from meeting point to fast = Z + m*C+y =X+ n*C+y - ( X+ m*C+y) .  Z is the distance from meeting point to entry and Z = X
        #     when using two slow pointer, it is actually  finding X and Z
        #
        if not head:
            return None
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            # if loop exist, then find the entry of loop
            if slow == fast:
                slow1 = head
                slow2 = slow
                while slow1!=slow2:
                    slow1 = slow1.next
                    slow2 = slow2.next
                return slow1 
        return None  
            

来源:力扣(LeetCode) 链接: 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

https://leetcode-cn.com/problems/linked-list-cycle-ii
力扣
Logo