[转]个数为n的只读数组包含元素[1, n-1],求其中一个重复的数
题目网址:
http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/Challenges/January2004.html
解答网址:
http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/solutions/January2004.html
题目:
Ponder This Challenge:
This month's puzzle was sent in by Joe Buhler.
It came from a SIGCSE meeting via Eric Roberts.
A read-only array of length n, with address from 1 to n inclusive,
contains entries from the set {1, 2, ..., n-1}.
By Dirichlet's Pigeon-Hole Principle there are one or more duplicated
entries. Find a linear-time algorithm that prints a duplicated value,
using only "constant extra space". (This space restriction is important;
we have only a fixed number of usable read/write
memory locations, each capable of storing an integer between 1 and n.
The number of such locations is constant, independent of n.
The original array entries can not be altered.) The algorithm should
be easily implementable in any standard programming language.
解答:
Solution:
This technique is known as Pollard's rho method; it was developed by John Pollard as a tool for integer factorization.
Let f(x) be the location of the array at address x.
a := f(f(n)) b := f(n) do while not (a=b) a:=f(f(a)) b:=f(b) end /* Now a=b can be reached at either 2k or k steps from n, */ /* where k is some integer between 1 and n. */ a:=n do while not (a=b) a:=f(a) b:=f(b) end print a
The pattern that you get, starting from n and repeatedly applying f (doing the table lookup), is a string of some length L>0 leading to a cycle of some length M, with L+M<n. (L is nonzero because n is outside the range of f.)
It is shaped like the Greek letter rho, hence its name. Our stopping count k is the least multiple of M greater than or equal to L, so that L \leq k < L+M < n.
更多材料:
Pollard's Rho Method
这是最好的时代,这是最坏的时代;这是智慧的年代,这是愚蠢的年代;这是信仰的时期,这是怀疑的时期;我们的前途拥有一切,我们的前途一无所有。
浙公网安备 33010602011771号