zoukankan      html  css  js  c++  java
  • leetcode------Linked List Cycle II

    标题: Linked List Cycle II
    通过率 30%
    难度 中等

    看升级版前还是先看下 Linked List Cycle I  

    看完第一个版本对于第二个版本会有一定的帮助,先了解环的结构。然后看下面的图片:

    假设快慢指针交汇处为为分红圈那个,环的起始点为k,那么:

    1、快指针走的路程是慢指针走的两倍。

    2、慢指针到相遇点时走的路径为:x+y

    3、快指针到相遇点走的路径为:x+y+z+y=x+2y+z

    4、又因为1,所有有 2(x+y)=x+2y+z

    5、得出:x=z

    于是我们发现了起点与重合点到循环起始点额距离是一样的。那么我们放两个指针从这两个地方开始遍历,当再次重合时便是循环开始点,具体代码如下:

     1 public class Solution {
     2     public ListNode detectCycle(ListNode head) {
     3         if(head==null) return null;
     4         if(head.next==null) return null;
     5         if(head.next.next==null) return null;
     6         
     7         ListNode slow=head;
     8         ListNode fast=head;
     9         
    10         while(fast!=null && fast.next!=null){
    11             slow=slow.next;
    12             fast=fast.next.next;
    13             if(fast==slow){
    14                 slow=head;
    15                 while(slow!=fast){
    16                      slow=slow.next;
    17                      fast=fast.next;
    18                     }
    19                 return fast;
    20             }
    21         }
    22 
    23         return null;
    24         
    25     }
    26 }
  • 相关阅读:
    Golang 读写文件的操作
    初始 Elasticsearch
    数据存储单位的换算(bytes、KB MB GB TB PB EB ZB YB DB NB)
    Go 语言类型元信息的通用结构 _type
    空接口
    HashMap和Hashtable的区别
    谈谈final, finally, finalize的区别
    理解AOP
    Struts2 OGNL概述
    Struts2原理
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4158226.html
Copyright © 2011-2022 走看看