Data structure for choosing random elements?

前端 未结 1 576
走了就别回头了
走了就别回头了 2020-12-25 14:18

Does anyone know of a data structure that supports the two operations efficiently?

  1. Insert a value into the data structure.
  2. Dequeue and return an entry
相关标签:
1条回答
  • 2020-12-25 15:01

    Yes. Use a vector.

    To insert, simply place at the end, and increment the size. To remove, pick an element at random, swap its contents with the end value, then pop off the end value (i.e., return the end value and decrement the vector's size).

    Both operations are amortised O(1).

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