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

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

从第一次相遇可得:slow: a + b; fast: 2(a + b). 并且2a + 2b = a + b + n(b + c), 可得a = (n - 1)b + nc,以此slow移到head,然后slow和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 fast = head.next.next;        ListNode slow = head.next;        while (fast != null && fast.next != null) {            if (fast == slow) {                break;            }            fast = fast.next.next;            slow = slow.next;        }        if (fast == null || fast.next == null) {            return null;        }        slow = head;        // 这里fast也是每次移一位!        while (fast != slow) {            slow = slow.next;            fast = fast.next;        }        return slow;    }}

你可能感兴趣的文章
vue 配置多页面应用的示例代码
查看>>
基于Vue实现图片在指定区域内移动的思路详解
查看>>
vue中各种通信传值方式总结
查看>>
vuex实现及简略解析(小结)
查看>>
useradd 无法打开 /etc/passwd
查看>>
Centos7修改root密码
查看>>
VMWare安装Centos7下载和安装教程
查看>>
CentOS 7 minimal 版本安装后网络配置
查看>>
python编程入门教程下载-Python编程从入门到实践的PDF教程免费下载
查看>>
用python画四叶草-python turtle工具绘制四叶草的实例分享
查看>>
python爬虫什么意思-Python为什么叫爬虫?Python与爬虫有什么关系?
查看>>
python代码示例-总算知道python入门代码示例
查看>>
python里怎么读取文件-python怎么读取文本文件
查看>>
python工资一般多少p-Python里的黄金库,学会了你的工资至少翻一倍
查看>>
python全套教程大全-千锋出品全套python视频教程,400大全集,你了解吗?
查看>>
python的优点有哪些-Python语言的特点有哪些
查看>>
python免费课程400节-北京市python儿童学编程
查看>>
python中文版下载-趣学python编程中文版 PDF 下载
查看>>
python入门教程pdf-python基础教程第4版pdf
查看>>
从零开始学习python编程-从0开始的Python学习014面向对象编程(推荐)
查看>>