Week 4
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. If the number of keys in the data type is even, find/remove the lower median.
分析(非原创)
基本看来就是用堆来实现一个寻找中位数的数据结构(数组能够做到常数时间定位中位数,但是排序最优是对数线性的),但是单纯一个堆是无法做到的,在网上查到使用一个最大堆和一个最小堆进行维护
设计
思路参考:https://blog.csdn.net/pngynghay/article/details/22209387
- 创建两个堆(一个小根堆、一个大根堆),堆大小至少为给定数据个数的一半,(size+1)/2,即向上取整;
- 假定变量mid用来保存中位数,取定第一个元素,赋值给mid,即作为初始的中位数;
- 依次遍历后面的每一个数据,如果比mid小,则插入大根堆;否则插入小根堆;
- 如果大根堆和小根堆上的数据个数相差为2,则将mid插入到元素个数较少的堆中,然后从元素个数较多的堆中删除根节点,并将跟节点赋值给mid;
- 重复步骤3和4,直到所有的数据遍历结束;
此时,mid保存了一个数,再加上两个堆中保存的数,就构成了给定数据的集合。
如果两个堆中元素个数相等,则mid即为最终的中位数;否则,元素较多的堆的根节点元素与mid的和求平均值,即为最终的中位数。
Randomized Priority Queue
题目
Describe how to add the methods s a m p l e ( ) \mathtt{sample()} sample() and d e l R a n d o m ( ) \mathtt{delRandom()} 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 s a m p l e ( ) \mathtt{sample()} sample() method should take constant time; the d e l R a n d o m ( ) \mathtt{delRandom()} delRandom() method should take logarithmic time. Do not worry about resizing the underlying array.
分析
就是在数组实现的堆上进行均匀随机采样的实现
设计
前一个方法就是直接在数组上均匀随机选择一个可好,后一个方法在选择之后,就执行和移去最大值一样的方法,将对应元素与最后一个元素调换,然后执行sink
方法回复堆有序
Taxicab Numbers
题目
A taxicab number is an integer that can be expressed as the sum of two cubes of positive integers in two different ways: a 3 + b 3 = c 3 + d 3 a^3 + b^3 = c^3 + d^3 a3+b