s --a-- begin --x----meet point
| |
|----------------|
1.fast goes two steps each time, while slow goes one step each time.
2.Supposing slow goes d, then fast goes 2*d. Considering the fast goes n loops, the distance of fast goes is d+ n*r, where r is the circle of loop. Then,
2*d = d+ n*r
d = n*r
d = a + x = n * r = (n-1)*r + r
= (n-1)*r + L-a // L is the length of the list
a = (n-1)*r + L-a-x
It means the distance from start point to the start of loop is equal to the distance from meet point moving to the start of loop.
Floyd's Cycle-Finding Algorithm
最新推荐文章于 2024-05-30 20:56:49 发布