Efficiently picking a random element from a chained hash table?

前端 未结 1 851
北荒
北荒 2021-01-31 21:38

Just for practice (and not as a homework assignment) I have been trying to solve this problem (CLRS, 3rd edition, exercise 11.2-6):

Suppose we have stored

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 22:25

    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)).

    0 讨论(0)
提交回复
热议问题