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?


判断一个链表是否有环。

题解:

设置两个指针p1和p2;

p1每次走一步,p2每次走两步,如果在这个过程中,p2为空,则没有环;否则两个指针必然相遇,则有环;

接下来找环的起点,将p1挪动到链表起始,p2保持在两指针相遇的地方不动,然后p1和p2分别每次走一步,则下一次相遇的地方为环的起点。

先贴代码如下:

 class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
} public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode p1 = head;
ListNode p2 = head; while(p2 != null){
p1 = p1.next;
p2 = p2.next;
if(p2 != null)
p2 = p2.next;
else
return null;
if(p1 == p2)
break;
} if(p2 == null)
return null;
p1 = head;
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}

证明如下(证明参考:http://stackoverflow.com/questions/2936213/explain-how-finding-cycle-start-node-in-cycle-linked-list-work

如上图所示,假设从链表起点到环的起点距离为m,从环的起点到p1和p2第一次相遇的地方距离为k,环的长度为n。设第一次相遇的时候p1走过了S步,则p2走过了2S步,所以

S = m + pn + k      (1)

2S = m + qn + k    (2)

其中p1绕圆走过了完整的p圈,p2绕圆完整的走过了q圈。

(1)式代入(2)式中得:2(m+pn+k) = m+qn + k  ->  m+k = (q - 2p)n   (3)

对于任意一个链表m和n是固定的,所以我们只要证明存在整数p,q,k使得(3)式成立即可。

去p = 0, k = mn-m, q = m, 则(3)式成立,所以p1,p2一定会相遇在距离环的起点(mn-m)的地方。

接下来证明如果使得p1回到环的起点,p2保持不动,两个指针以相同的速度前行,则下一次相遇的地方一定是环的起点。

从(3)式可以看出,m+k是环的长度的整数倍,所以p2从相遇的地方走m步,一定回到环的起点,而p1从链表起点走m步也走到环的起点,所以p1和p2以相同的速度前进,下一次相遇的地方一定的环的起点。

证毕。

【leetcode刷题笔记】Linked List Cycle II的更多相关文章

  1. 【leetcode刷题笔记】Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  2. 【leetcode刷题笔记】Palindrome Partitioning II

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

  3. 【leetcode刷题笔记】Single Number II

    Given an array of integers, every element appears three times except for one. Find that single one. ...

  4. 【leetcode刷题笔记】Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  5. 【leetcode刷题笔记】Jump Game II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  6. 【leetcode刷题笔记】Unique Paths II

    Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...

  7. 【leetcode刷题笔记】Spiral Matrix II

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...

  8. LeetCode刷题笔记和想法(C++)

    主要用于记录在LeetCode刷题的过程中学习到的一些思想和自己的想法,希望通过leetcode提升自己的编程素养 :p 高效leetcode刷题小诀窍(这只是目前对我自己而言的小方法,之后会根据自己 ...

  9. LeetCode刷题笔记 - 12. 整数转罗马数字

    学好算法很重要,然后要学好算法,大量的练习是必不可少的,LeetCode是我经常去的一个刷题网站,上面的题目非常详细,各个标签的题目都有,可以整体练习,本公众号后续会带大家做一做上面的算法题. 官方链 ...

  10. 18.9.10 LeetCode刷题笔记

    本人算法还是比较菜的,因此大部分在刷基础题,高手勿喷 选择Python进行刷题,因为坑少,所以不太想用CPP: 1.买股票的最佳时期2 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. ...

随机推荐

  1. (四)Thymeleaf标准表达式之——[3->6] 操作符(文本、算术、布尔、比较及相等)

    2.3 文本操作符 模板名称:text.html 连接符: +   可以是任意字符和表达式等 文本替换符:|    不能表达出条件表达式(官网:只能是变量表达式) e.g. 1.<span th ...

  2. IOS开发准备 资料集锦

    1 http://blog.csdn.net/column/details/xfzl-kykhd.html 2

  3. 安装Geo-IP

    安装指令例如以下所看到的,跟着步骤一步一步运行就可以.使用root权限,假设不是的话,请依据情况加上sudo权限命令. cd /tmp wget http://geolite.maxmind.com/ ...

  4. Linux中终端和控制台区别

    Linux中终端和控制台区别: 终端:英文名叫terminal 控制台:英文名叫console 两者区别要从以前的多人使用的计算机开始 以前,由于计算机很昂贵,所用一台计算机一般由多个人同时使用.这样 ...

  5. Redis源码阅读-Adlist双向链表

    Redis源码阅读-链表部分- 链表数据结构在Adlist.h   Adlist.c Redis的链表是双向链表,内部定义了一个迭代器. 双向链表的函数主要是链表创建.删除.节点插入.头插入.尾插入. ...

  6. php 微信开发之新增上传/获取下载临时素材

    php 微信开发之新增上传/获取下载临时素材 代码 <?php define("AppID","");//你的id define("AppSec ...

  7. Java中的使用了未经检查或不安全的操作(类前加:@SuppressWarnings("unchecked"))

    Java中的使用了未经检查或不安全的操作 如此解决就可以了 类前面加@SuppressWarnings("unchecked") @SuppressWarnings("u ...

  8. python write file

    fileHandle = open ( 'test.txt', 'a' ) fileHandle.write ( '\n\nBottom line.' ) fileHandle.close() 转自: ...

  9. 写出完美的snprintf

    平时公司的代码安全扫描会给出不安全代码的告警,其中会检查代码中间的strcpy和sprintf函数,而要求使用strncpy和snprintf.今天我们讨论一下怎样写出完美的snprintf. snp ...

  10. 如何通过Google访问外网

    修改host: https://laod.cn/hosts/2017-google-hosts.html google中文: https://www.google.com.hk/ 弄好前两项后,可以再 ...