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.

  • 相关阅读:
    Redis企业级数据备份与恢复方案
    使用canal增量同步mysql数据库信息到ElasticSearch
    SpringBoot基于数据库实现简单的分布式锁
    SpringBoot+ShardingSphere实现分库分表 + 读写分离
    SpringBoot 使用JestClient操作Elasticsearch
    Java 操作 MongoDB
    VS C#开发中WinForm中Setting.settings的作用
    Sql 触发器禁用和启用
    ROW_NUMBER over (order by **)
    Aspen 安装
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3787951.html
Copyright © 2011-2022 走看看