zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    hdu 4612 Warm up 桥缩点
    树上的一个题目
    2013 ACM/ICPC Asia Regional Online —— Warmup2
    hdu 3308 LCIS 线段树
    最近计划
    hdu 2121 , hdu 4009 无定根最小树形图
    POJ 3164 Command Network 最小树形图模板
    过滤器和拦截器
    struts中的请求数据自动封装
    struts中获取域
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5506539.html
Copyright © 2011-2022 走看看