Get random element and remove it

前端 未结 3 2250
眼角桃花
眼角桃花 2021-02-14 15:30

Problem: I need to get a random element for a container and also delete it from that container. Container does not need to be sorted. I dont care about the order.

3条回答
  •  自闭症患者
    2021-02-14 16:14

    Yes, there is a solution, a well-balanced binary tree.

    One each node you would need to store the number of nodes on each side. From this it is O(log N) to find the nth element.

    Removing the nth element is also O(log N) as you have to traverse back up to tree to correct all the counts. Any rebalancing would be O(log N) too at most.

    A tree is considered well balanced if no leaf node is 2 nodes deeper than another. Look up AVL trees to get a rabalancing algorithm.

    It would actually be good if the standard library "opened" the use of the trees used for std::set and std::map as a public interface for use in custom trees.

提交回复
热议问题