Floyd's cycle-finding algorithm

来源:互联网 发布:反监听软件 编辑:程序博客网 时间:2024/05/22 16:27

From Quora

How does Floyd's cycle-finding algorithm work?

I understand that tortoise and hare's meeting concludes the existence of loop, but how does moving tortoise to beginning of linked list while keeping the hare at meeting place, followed by moving both one step at a time make them meet at starting point of cycle?

A lot of good perspectives.  The way I remember it is like Namrata's answer but, I think, a bit simpler without needing to explicitly manipulate any equations or worry about how many times the cycle is traversed.


We only need to consider two positions, s - the start of the cycle, and s+x, where x is the offset from the cycle start where the two pointers meet.

When the slow pointer traveled s+x, the fast one will have traveled an additional distances+x from the offset position x along the cycle.  This extras+x distance brought it back to the same position along the cycle (offsetx). 

That means if moving a distance s+x from that offset brings the pointer back to the offsetx, then moving x less from that position, ors, will result in the pointer being at the start of the cycle - positions = offset 0. 

Therefore, starting the formerly-fast pointer from where they met (offset x along the cycle), and the formerly-slow pointer at the beginning, and moving both pointers at equal pace, afters iterations, the formerly-fast one will be at the cycle start s and, the formerly-slow one will also be at the cycle starts.




Fast pointer have to meet the slow one because their distance is s and the different of velocity is 1.
And when they meet, the slow pointer won't go further then (s+x) because s/1<(s+x)/1.(this circumstance will happen when the slow one get into the circle and the fast one is in the x)

0 0
原创粉丝点击