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.

  • 相关阅读:
    MVC的12种ActionResult介绍以及应用示例【转】
    SQL Server抛出异常信息 RAISERROR
    lambda select和where区别
    JS中的原型对象与构造器
    JS原型的动态性
    关于困惑已久的var self=this的解释
    JS原型对象的问题
    再谈.NET委托(delegate、Func<>)
    在函数作用域嵌套下使用this
    Python 易错点
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3787951.html
Copyright © 2011-2022 走看看