问题
How would you pick a uniform random element in linked list with unknown length in one pass or if not two passes?
回答1:
Use reservoir sampling http://en.wikipedia.org/wiki/Reservoir_sampling . You need only one pass of the data.
For picking one element:
- Pick first element (probability 1)
- Later, for kth element pick it with probability 1/k (i.e. replace the existing selection with kth element)
I will let you prove that this results in uniform selection of elements.
来源:https://stackoverflow.com/questions/9401375/how-would-you-pick-a-uniform-random-element-in-linked-list-with-unknown-length