• leetcode算法


    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?

    解题思想:

    用两个指针来操作本题,一个慢指针slow,一个快指针fast,慢指针一下走一步,慢指针一下走两不,如果不含环,那么当快指针到尾部的时候 return null,如果有环,那么一定存在一点 使得fast=slow.

    我在网上找了一个图:Y表示入口,a表示起始点到Y的距离,Z表示相遇点,b表示入口到相遇点的距离, c表示Z跑到Y的距离。 因为有 快指针每次走两步,慢指针每次走一步,推得 2(a+b)=kn+a+b,

    化简,  a=kn-b,我们观察这表示什么意思了,就是从X->Y 就相当与  另外一个指针转了n个圈,然后减去b的距离 也就是到达了位置Y。所以最终会在Y相遇。

    问题代码(这个代码没有通过leetcode所有测试用例,实在不知道为什么,大神们指导指导下):

      public ListNode detectCycle(ListNode head) {
            if(head==null||head.next==null)return null;
            ListNode fast=head;
            ListNode slow=head;
            while(fast!=null&&fast.next!=null){
                slow=slow.next;
                fast=fast.next.next;
                if(fast==null){//判定fast有没有到达结尾。
                    return null;
                }
                if(fast==slow){
                    break;
                }
            }
            slow=head;
            while(fast!=slow){
                slow=slow.next;
                fast=fast.next;
            }
            return slow;
            
        }
    View Code

    全部通过代码:

       public ListNode detectCycle(ListNode head) {
            if(head==null||head.next==null)return null;
            ListNode fast=head;
            ListNode slow=head;
            while(fast!=null&&fast.next!=null){
                slow=slow.next;
                fast=fast.next.next;
                if(fast==null){//判定fast有没有到达结尾。
                    return null;
                }
                if(fast==slow){
                    slow=head;
                    while(fast!=slow){
                        slow=slow.next;
                        fast=fast.next;
                    }
                    return slow;
                }
            }
            return null;
        }
  • 相关阅读:
    建立文件结构
    PCL类的设计结构
    如何编写新的PCL类
    PCL推荐的命名规范(2)
    PCL推荐的命名规范(1)
    PCL中异常处理机制
    如何增加新的PointT类型
    hdoj 1728 逃离迷宫
    ny710 外星人的供给站
    ny714 Card Trick
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5506539.html
Copyright © 2020-2023  润新知