Dynamic median. Design a data type that supports insert in logarithmic time, find-the-median in constant time, and remove-the-median in logarithmic time.
描述: 设计支持在对数时间内插入的数据类型,在常数时间内查找中位数,并在对数时间内删除中位数。
解答: 思路:使用一个最大堆一个最小堆。
- 插入中位数操作:如果仅有一个节点,那么这个数就是中位数。如果有两个节点,一个放入最小堆,一个放入最大堆。之后插入新节点,先和最大堆的根节点比较,如果小于或等于根节点值就插入最大堆,否则插入最小堆。另外,如果最大最小堆的节点数目相差大于1,需要进行调整,删除较大堆的根节点,插入到较小堆中。
- 删除中位数操作,如果两边高度相同,随机删除其中一个堆的根节点,否则,删除较大堆的根节点。
-
Randomized priority queue. Describe how to add the methods sample() and delRandom() to our binary heap implementation. The two methods return a key that is chosen uniformly at random among the remaining keys, with the latter method also removing that key. The sample() method should take constant time; the delRandom() method should take l