LEETCODE —— Linked List Cycle [Floyd's cycle-finding algorithm]
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
佛洛依德龟兔算法
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 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]的更多相关文章
- 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 ...
- Floyd's Cycle Detection Algorithm
Floyd's Cycle Detection Algorithm http://www.siafoo.net/algorithm/10 改进版: http://www.siafoo.net/algo ...
- LeetCode & linked list bug
LeetCode & linked list bug add-two-numbers shit test /** * Definition for singly-linked list. * ...
- [LeetCode] Linked List Cycle II 单链表中的环之二
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...
- [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 ...
- [LeetCode]Linked List Cycle II解法学习
问题描述如下: Given a linked list, return the node where the cycle begins. If there is no cycle, return nu ...
- 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 ...
- LeetCode——Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...
- [算法][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 ...
随机推荐
- 我收录整理的优秀OC技术类文章
自定义导航按钮UIBarButtonItem 关于导航栏的六个小技巧 ios开发的一些小技巧篇一 制作一个可以滑动操作的 Table View Cell - IOS - 伯乐在线 一个 ...
- web 乱码摘抄
JavaWeb--中文乱码小结 JavaWeb--中文乱码小结 0.纯粹html乱码: 换个editor吧(有时候notepad都比sublime_text好用),最好是在<head>&l ...
- HTML5 拖动
触发的事件有:dragstart事件.drag事件和dragend事件. 按下鼠标键并开始移动鼠标的时候,会在被拖拽的元素上触发dragstart事件.这时候光标变成”不能放”符号(圆环中有一条反斜线 ...
- SSH框架
一,Struts2框架部署 1,搭建Struts2的jar包 1.1,Struts2所需各个jar包的作用 asm-3.3.jar 操 ...
- POJ 3683 Priest John's Busiest Day (2-SAT)
题意:有n对新人要在同一天结婚.结婚时间为Ti到Di,这里有时长为Si的一个仪式需要神父出席.神父可以在Ti-(Ti+Si)这段时间出席也可以在(Di-Si)-Si这段时间.问神父能否出席所有仪式,如 ...
- struct与union字节大小的终极解释
1.字节对齐的细节和编译器实现相关,但一般而言,如在windows下,就VC而言,满足一下三个准则:1) 结构体变量的首地址能够被其最宽基本类型成员的大小所整除:2) 结构体每个成员相对于结构体首地址 ...
- Go语言并发编程示例 分享(含有源代码)
GO语言并发示例分享: ppt http://files.cnblogs.com/files/yuhan-TB/GO%E8%AF%AD%E8%A8%80.pptx 代码, 实际就是<<Go ...
- iOS 截图功能
步骤: 当我们所需截的图的大小超过我们屏幕的大小时,可以用UIScrollView作为底图,这样就可以截图我们所需的大小,即 UIScrollView *scrollView = self.view. ...
- theano 实现图像局部对比度归一化
很多时候我们需要对图像进行局部对比度归一化,比如分块CNN的预处理阶段.theano对此提供了一些比较方便的操作. 局部归一化的一种简单形式为: 其中μ和σ分别为局部(例如3x3的小块)的均值和标准差 ...
- [转]使用Scrapy建立一个网站抓取器
英文原文:Build a Website Crawler based upon Scrapy 标签: Scrapy Python 209人收藏此文章, 我要收藏renwofei423 推荐于 11个月 ...