• linked-list-cycle-ii 链表中的环


    题目:

    对于一个给定的链表,返回环的入口节点,如果没有环,返回null
    拓展:
    你能给出不利用额外空间的解法么?

    Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
    Follow up:
    Can you solve it without using extra space?

    代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if(head == NULL)
    13             return NULL;
    14         ListNode* slow = head;
    15         ListNode* fast = head;
    16         while(fast != NULL && fast->next != NULL){
    17             fast = fast->next->next;
    18             slow = slow->next;
    19             if(slow == fast)
    20                 break;
    21         }
    22         if(fast == NULL || fast->next == NULL)
    23             return NULL;
    24         fast = head;
    25         while(fast != slow){
    26             fast = fast->next;
    27             slow = slow->next;
    28         }
    29         return slow;
    30     }
    31 };

    我的笔记:

    1)同linked-list-cycle-i一题,使用快慢指针方法,判定是否存在环,并记录两指针相遇位置(Z);
    2)将两指针分别放在链表头(X)和相遇位置(Z),并改为相同速度推进,则两指针在环开始位置相遇(Y)。

    证明如下:
    如下图所示,X,Y,Z分别为链表起始位置,环开始位置和两指针相遇位置,则根据快指针速度为慢指针速度的两倍,可以得出:
    2*(a + b) = a + b + n * (b + c);即
    a=(n - 1) * b + n * c = (n - 1)(b + c) +c;
    注意到b+c恰好为环的长度,故可以推出,如将此时两指针分别放在起始位置和相遇位置,并以相同速度前进,当一个指针走完距离a时,另一个指针恰好走出 绕环n-1圈加上c的距离。
    故两指针会在环开始位置相遇。
    注意:快慢指针第一次相遇的时候一定是在第一圈内,因为快指针对慢指针来说,每次两者之间的距离都在 -1,而当慢指针刚进入环时,与快指针的距离 <= b + c,而慢指针距离环的距离也一定 <= b + c,因此,快指针一定能在慢指针进入环后第一圈追上。
     
  • 相关阅读:
    OpenCV 3.2 Viz 3D可视化
    OpenCV 3.2 FlannBasedMatcher
    ORB-SLAM (四)Initializer单目初始化
    ORB-SLAM(十二)优化
    ORB-SLAM(十一)EPnP
    ORB-SLAM(十)LoopClosing Sim3求解
    ORB-SLAM(十)LoopClosing
    ORB-SLAM(九)LocalMapping
    ORB-SLAM(八)ORBmatcher 特征匹配
    ORB-SLAM(七)ORBextractor 特征提取
  • 原文地址:https://www.cnblogs.com/john1015/p/13255817.html
Copyright © 2020-2023  润新知