leetcode

    xiaoxiao2021-03-25  79

    题意:

    如果一个链表存在圈,返回圈的开始处,如果不存在,返回null

    分析:

    如果一个链表有圈会怎样? ==》 指针顺序遍历永远遍历不到空 ,且会重复走一段路 ==》 如果是两个快慢指针,那么它们一定会相遇 ==》在哪里相遇?

    我认为最有效的两个思维方式:举例子和画图。

    来:        

                       * —— *

                       |          |

    *——*——*——*

    在这个例子中,我们发现它们在右上角那个点相遇

    继续:

                       * ---* ---*

                       |           |

    *——*——*——*

    在这个例子中我们发现他们在上面中间那个位置相遇

    通过动态的模拟这个过程和理论分析,很容易就发现,

    1 每一步fast比slow多走1

    2 刚刚slow进入圈的时候,fast已经在圈内走了直线部分的距离       (暂时不考虑fast走了多圈的情况,因为可能不用考虑,fast走了那么多圈,以后slow也要走,只看相对)

    3 由2可得:fast距离slow的距离为 : 圈减去直线 (因为是fast追slow)

    3 1.2结合得出:经过圈周长减去直线距离那么多步相遇。

    4 也就是说经过直线步,slow就走到循环点

    5 那么我们把 fast放到直线开始,即最开始,同时走,再次相遇点即圈开始点

    其实有些因素还没考虑,例子也没有包含所有情况。但是这样实现的代码还是直接过了:

    /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head==null || head.next==null){ return null; } ListNode slow = head; ListNode fast = head; do{ if(slow.next == null) return null; slow = slow.next; if(fast.next == null || fast.next.next == null) return null; fast = fast.next.next; }while(slow != fast); fast = head; while(slow != fast){ fast = fast.next; slow = slow.next; } return slow; } }

    转载请注明原文地址: https://ju.6miu.com/read-17881.html

    最新回复(0)