Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None:
return False
rabbit = turtle = head
while rabbit.next and rabbit.next.next:
turtle = turtle.next
rabbit = rabbit.next.next
if rabbit == turtle:
return True
return False
 解法,两个指针同时前移,当二者碰面则为有环,遇到None则为无环。 i.e.

佛洛依德龟兔算法

 这个猜想其实早就被证明了,wiki: http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare ,so更详细的解释在此:
 

Let me try to clarify the cycle detection algorithm that is provided at http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare in my own words.

I refer to the figure  in my explanation.

How it works

Let's have a tortoise and a hare (name of the pointers) pointing to the beginning of the list with a cycle.

Let's hypothesize that if we move tortoise 1 step at a time, and hare 2 steps at a time, they will eventually meet at a point. Let's show that first of all this hypothesis is true.

The figure illustrates a list with a cycle. The cycle has a length of n and we are initially m steps away from the cycle. Also let's say that the meeting point is k steps away from the cycle beginning and tortoise and hare meets after a total of i steps.

The following 2 conditions must hold:

1) i = m + p * n + k

2) 2i = m + q * n + k

The first one says that tortoise moves i steps and in these i steps it first gets to the cycle. Then it goes through the cycle p times for some positive number p. Finally it goes over k more nodes until it meets hare.

A similar is true for hare. It moves 2i steps and in these 2i steps it first gets to the cycle. Then it goes through the cycle q times for some positive number q. Finally it goes over k more nodes until it meets tortoise.

Therefore,

2 ( m + p * n + k ) = m + q * n + k

=> 2m + 2pn + 2k = m + nq + k

=> m + k = ( q - 2p ) n

Among m, n, k, p, q, the first two are properties of the given list. If we can show that there is at least one set of values for k, q, p that makes this equation true we show that the hypothesis is correct.

One such solution set is as follows:

p = 0

q = m

k = m n - m

We can verify that these values work as follows:

m + k = ( q - 2p ) n

=> m + mn - m = ( m - 2*0) n

=> mn = mn.

For this set, i is

i = m + p n + k

=> m + 0 * n + mn - m = mn.

Of course, you should see that this is not necessarily the smallest i possible. In other words, tortoise and hare might have already met before many times. However, since we show that they meet at some point at least once we can say that the hypothesis is correct. So they would have to meet if we move one of them 1 step, and the other one 2 steps at a time.

Now we can go to the second part of the algorithm which is how to find the beginning of the cycle.

Cycle Beginning

Once tortoise and hare meet, let's put tortoise back to the beginning of the list and keep hare where they met (which is k steps away from the cycle beginning).

The hypothesis is that if we let them move at the same speed (1 step for both), the first time they ever meet again will be the cycle beginning.

Let's prove this hypothesis.

Let's first assume some oracle tells us what m is.

Then, if we let them move m + k steps, tortoise would have to arrive at the point they met originally (k steps away from the cycle beginning - see in the figure).

Previously we showed that m + k = (q - 2p) n.

Since m + k steps is a multiple of cycle length n, hare, in the mean time, would go through the cycle (q-2p) times and would come back to the same point (k steps away from the cycle beginning).

Now, instead of letting them move m + k steps, if we let them move only m steps, tortoise would arrive at the cycle beginning. Hare would go be k steps short of completing (q-2p) rotations. Since it started k steps in front of the cycle beginning, hare would have to arrive at the cycle beginning.

As a result, this explains that they would have to meet at the cycle beginning after some number of steps for the very first time (very first time because tortoise just arrived at the cycle after m steps and it could never see hare which was already in the cycle).

Now we know that the number of steps we need to move them until they meet turns out to be the distance from the beginning of the list to the cycle beginning, m. Of course, the algorithm does not need to know what m is. It will just move both tortoise and hare one step at a time until they meet. The meeting point has to be the cycle start and the number of steps must be the distance (m) to the cycle beginning. Assuming we know the length of the list, we can also, compute the length of the cycle of subtracting m from the list length.

 

LEETCODE —— Linked List Cycle [Floyd's cycle-finding algorithm]的更多相关文章

  1. LeetCode Linked List Cycle II 和I 通用算法和优化算法

    Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cyc ...

  2. Floyd's Cycle Detection Algorithm

    Floyd's Cycle Detection Algorithm http://www.siafoo.net/algorithm/10 改进版: http://www.siafoo.net/algo ...

  3. LeetCode & linked list bug

    LeetCode & linked list bug add-two-numbers shit test /** * Definition for singly-linked list. * ...

  4. [LeetCode] Linked List Cycle II 单链表中的环之二

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

  5. [LeetCode] Linked List Cycle 单链表中的环

    Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...

  6. [LeetCode]Linked List Cycle II解法学习

    问题描述如下: Given a linked list, return the node where the cycle begins. If there is no cycle, return nu ...

  7. LeetCode——Linked List Cycle

    Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...

  8. LeetCode——Linked List Cycle II

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

  9. [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环

    题目要求 Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you so ...

随机推荐

  1. WC项目要求

    #include "stdio.h" #include "string.h" #include "stdlib.h" int charcal ...

  2. 爱上iOS单元测试系列之爱上她就要先了解她:单元测试入门

    前言 对于单元测试一开始我是拒绝的.单元测试是一个什么东东,因为我喜欢做iOS开发是因为喜欢写APP的啊,一切和这一目标不相干的东西我没兴趣啊,所以从事iOS开发几年都没去深入学习过单元测试(主要是之 ...

  3. mysql 新建用户、授权、远程访问

    新建用户 insert into mysql.user(Host,User,Password) values("localhost","u",password( ...

  4. AFNetworking3.0使用

    AFHTTPSessionManager: 根据这个对象可以对请求千设置一些参数和状态 //得到一个session manager AFHTTPSessionManager *manager = [A ...

  5. jsp中的正则表达式

    sp中${}----是EL表达式的常规表示方式目的是为了获取{}中指定的对象(参数.对象等)的值如:${user.name}<====>User user = (User)request( ...

  6. Spark的Straggler深入学习(1):如何在本地图形监控远程Spark的GC情况——使用java自带的jvisualvm

    一.本文的目的       Straggler是目前研究的热点,Spark中也存在Straggler的问题.GC问题是总所周知的导致Straggler的重要因素之一,为了了解GC导致的Straggle ...

  7. 谈谈自己对C语言中函数指针的一些理解 (第一次写博客,有点小兴奋哈)

    1.函数指针声明的格式及简单的使用 (1)格式:(返回值)(*函数指针名)(参数列表)    例如:声明一个无参数无返回值的函数指针(void)(*p)(void). (2)将函数指针指向某个无参数无 ...

  8. Noi2011 阿狸的打字机

    ..] of longint; e,q,fa,ps,pt,fail,ans:..] of longint; trie:..,..] of longint; c:..] of longint; s:.. ...

  9. HTML标签整理

    第一次接触动态网站的相关代码,对程序里HTML的标签不理解.在这里会把碰到的HTML标签整理出来,持续更新. 1.<form></form>:用于声明表单,定义采集数据的范围, ...

  10. 【转】Unity3d + NGUI 的多分辨率适配

    原文地址:http://www.cnblogs.com/cqgreen/p/3348154.html   一.当下移动设备的主流分辨率(数据来自“腾讯分析移动设备屏幕分辨率分析报告”) 1.1 iOS ...