This is a cycle detection algorithm. Two pointers are used in this algorithm.
It is also called Floyd's cycle-finding algorithm, this is the link to wikipedia:
Tortoise and the Hare.
If there exists a cycle in X[0..n] from X[u] to X[u+v]. We have X[u] = X[u + kv]
In the first phase, we initialize two pointers, a tortoise with speed 1 and a hare with speed 2. They will meet at some point in the cycle. X[i] = X[2i].
In the second phase, we set the tortoise to X[0], and set the hare speed to 1.They will meet at X[u] = X[2i + u] (because 2i - i must be kv so that they could meet the first time).
Then we could easily find v.
No comments:
Post a Comment