zoukankan      html  css  js  c++  java
  • LC.142. Linked List Cycle II

    https://leetcode.com/problems/linked-list-cycle-ii/description/
    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Note: Do not modify the linked list.
    思路:
    https://www.cnblogs.com/hiddenfox/p/3408931.html
    第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

    因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。

    设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。slow和fast的速度分别是qs,qf。



    time: O(n) space: O(1)


     1 public ListNode detectCycle(ListNode head) {
     2         if (head == null || head.next == null) return null ;
     3         ListNode fast = head, slow = head ;
     4         while (fast != null && fast.next != null){
     5             fast = fast.next.next ;
     6             slow = slow.next ;
     7             //FAST 和 SLOW 相遇的位置 z,这时候重新开一个SLOW2从头出发, 只要SLOW2 碰上SLOW 就是圆环开始的位置
     8             if (fast == slow ){
     9                 ListNode slow2 = head;
    10                 while (slow != slow2){
    11                     slow = slow.next ;
    12                     slow2 = slow2.next;
    13                 }
    14                 return slow ;
    15             }
    16         }
    17         return null;
    18     }
  • 相关阅读:
    springboot接口测试
    谷粒学院_day08_课程管理_添加课程之课程发布(后端开发)
    谷粒学院_day03_vue组件
    谷粒学院_day03_vue固定代码抽取
    vue自定义事件
    vue插槽slot
    vue基本语法
    Vue之axios异步通信
    无归岛[HNOI2009]
    仓库建设[ZJOI2007]
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8464061.html
Copyright © 2011-2022 走看看