Efficiently picking a random element from a chained hash table?

北城以北 提交于 2019-12-02 18:47:42

Repeat the following steps until an element is returned:

  • Randomly select a bucket. Let k be the number of elements in the bucket.
  • Select p uniformly at random from 1 ... L. If p <= k then return the pth element in the bucket.

It should be clear that the procedure returns an element uniformly at random. We are sort of applying rejection sampling to the elements placed in a 2D array.

The expected number of elements per bucket is n / m. The probability that the sampling attempt succeeds is (n / m) / L. The expected number of attempts needed to find a bucket is therefore L * m / n. Together with the O(L) cost of retrieving the element from the bucket, the expected running time is O(L * (1 + m / n)).

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