How would you pick a uniform random element in linked list with unknown length?

ⅰ亾dé卋堺 提交于 2019-12-17 20:03:20

问题


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:

  1. Pick first element (probability 1)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!