博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leedcode 142] Linked List Cycle II
阅读量:4315 次
发布时间:2019-06-06

本文共 999 字,大约阅读时间需要 3 分钟。

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:

Can you solve it without using extra space?

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

 我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。

/** * 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) return null;        ListNode fast=head;        ListNode slow=head;        while(fast!=null&&fast.next!=null){            fast=fast.next.next;            slow=slow.next;            if(fast==slow) break;        }        if(fast==null||fast.next==null) return null;        fast=head;        while(fast!=slow){            fast=fast.next;            slow=slow.next;        }        return fast;    }}

 

转载于:https://www.cnblogs.com/qiaomu/p/4678874.html

你可能感兴趣的文章
Lucene、ES好文章
查看>>
android 生命周期
查看>>
jquery--this
查看>>
MySQL 5.1参考手册
查看>>
TensorFlow安装流程(GPU加速)
查看>>
OpenStack的容器服务体验
查看>>
BZOJ1443: [JSOI2009]游戏Game
查看>>
【BZOJ 4059】 (分治暴力|扫描线+线段树)
查看>>
BZOJ 1066 蜥蜴(网络流)
查看>>
提高批量插入数据的方法
查看>>
Linux重启Mysql命令
查看>>
前端模块化:RequireJS(转)
查看>>
linux 内核的优化
查看>>
Spark笔记之DataFrameNaFunctions
查看>>
Oracle 时间函数 (转)
查看>>
近端梯度算法(Proximal Gradient Descent)
查看>>
DRM-内容数据版权加密保护技术学习(中):License预发放实现 (转)
查看>>
TCP与UDP协议
查看>>
php上传文件如何保证上传文件不被改变或者乱码
查看>>
目录遍历代码
查看>>