zoukankan      html  css  js  c++  java
  • [LeetCode] Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Follow up: Can you solve it without using extra space?

    比较直接的方法,时间复杂度O(n^2),指针p每次往下走一步,指针t依次指向head到p之间的结点,判断p->next是不是t,知道p指向末尾结点,或者p->next==t.但提交结果显示 “Time Limit Exceeded”,编程如下:

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
    
            if(head==NULL)
                return NULL;
    
            ListNode *p=head,*t;
    
            while(p!=NULL)
            {
              t = head;
              if(p->next==p)
                  return p;
              while(t!=p)
              {
                if(p->next == t)
                    return t;
                t = t->next;
              }
              p = p->next;
            }    
    
        return NULL;
        }//end detectCycle
    };//end class

    所以要寻求更加简单的方法!看下面龟兔赛跑的故事,明明是数学题好不好,兔子每次跑2个结点,乌龟每次跑1个结点,看下面leetcode讨论中大神stackpop的代码和解释:

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            ListNode* slow = head;
            ListNode* fast = head;
            do{
                if( !slow || !fast ) return NULL;
                slow = slow->next;
                fast = fast->next;
                if( fast ) fast = fast->next;
                else return NULL;
            }while( slow != fast );
            slow = head;
            while( slow != fast ){
                slow = slow->next;
                fast = fast->next;
            }
            return slow;
        }
    };

    It is a famous known problem Hare and Tortoise  Length of head to cycle started node:x

    Length of the cycle: y

    Let hare run two steps while tortoise runs one step

    while both of them entered the cycle, the hare is definetly to overlap the tortoise at some node, we define it as m:

    The hare totally runs: x + ky + m The tortoise totally runs: x + ty + m Thus, ky = 2ty + x + m we have (x + m) mod y = 0 We can conclude that if the hare run more x steps, it will reach the cycle's starting node.

  • 相关阅读:
    2018.11.21 struts2获得servletAPI方式及如何获得参数
    2018.11.20 Struts2中对结果处理方式分析&struts2内置的方式底层源码剖析
    2018.11.19 Struts2中Action类的书写方式
    2018.11.18 Sturts2配置详解&常量配置进阶
    2018.11.17 Struts2框架入门
    需求分析
    可行性研究
    防火墙
    homework1
    静态网页开发技术
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3787951.html
Copyright © 2011-2022 走看看