zoukankan      html  css  js  c++  java
  • 数学公式推导法解决问题

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

    ///

    如果按照常规的思想,我们可以遍历一遍节点,使用O(n)的空间复杂度,当然这就不需要人来思考了

    ///以刷题的要求,首先判断是否有圈快慢法,然后相遇后我们发现,位置之间的联系是存在的,

    假设几个未知数,来求解方程,利用方程来求解的思想在小学奥数中想必经常出现

    在我们刷题过程我们应该经常使用。

    点的位置要有参考系,我想这点大家都懂

    所以必须,由head开始,circlestarting-point(CP)点的距离为L,meeting-point(M)到CP的距离为S

    M到CP---一圈的距离为Y,每圈长度为C,于是我们可以得到几个方程。

       2 * T = T + N1 * C    N1=0,1,2...
    

    N1为快慢指针跑的圈数差

       T = N1 * C
    
       2 * T = L + N2 * C + S    N2=0,1,2...
    

    N2为慢指针跑的圈数

    整理后(2N1-N2)×C=L+S

    设N3于是

       N3 * C = L + S  
      C=L+Y
      (N3 - 1) * C + S + Y = L + S
    
      (N3 - 1) * C + Y = L
    

    class Solution {
        public:
            ListNode *detectCycle(ListNode *head) {
                ListNode* dummy=new ListNode(-1);
                dummy->next=head;
                ListNode *slow=dummy, *fast=dummy;
                bool flag=false;
                while(fast && fast->next){
                    slow=slow->next;
                    fast=fast->next->next;
                    if(fast==slow)  { flag=true; break; }
                }
                if(!flag)   return NULL;
                ListNode* result=dummy;
                while(result != slow){
                    result=result->next;
                    slow=slow->next;
                }
                return result;
            }
        };

  • 相关阅读:
    vue的组件名称问题
    vue引入js文件时报This dependency was not found:错误
    vue中input输入第一个字符时,光标会消失,需要再次点击才能输入
    vue中url带有#号键,去除方法
    vue路由机制导致的坑,坑,坑
    Python文件读取和数据处理
    python面向对象
    Python PIL库学习笔记
    汉诺塔的python 动画演示
    十九大报告词频分析
  • 原文地址:https://www.cnblogs.com/fenglongyu/p/7779021.html
Copyright © 2011-2022 走看看