Randomized priority queue

Describe how to add the methods \mathtt{sample()}sample() and \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 \mathtt{sample()}sample() method should take constant time; the \mathtt{delRandom()}delRandom() method should take logarithmic time. Do not worry about resizing the underlying array.

public class PriorityQueue {
    /*
    Question 1
    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.
     */

    class MediaHeap {
        private MaxPQ<Integer> left;
        private MinPQ<Integer> right;
        private int L;
        private int R;

        MediaHeap() {
            left = new MaxPQ<Integer>();
            right = new MinPQ<Integer>();
        }

        public double findMedian() {
            int L = left.size();
            int R = right.size();
            if (L == R)
                return ((double)left.max() + (double)right.min()) / 2;
            else if (L > R)
                return left.max();
            else
                return right.min();
        }

        public void insert(int key) {
            double median = findMedian();
            int L = left.size();
            int R = right.size();
            if (key <= median) {
                left.insert(key);
                if (L - R > 1)
                    right.insert(left.delMax());
            }
            else {
                right.insert(key);
                if (R - L > 1)
                    left.insert(right.delMin());
            }
        }

        public void removeMedian() {
            int L = left.size();
            int R = right.size();
            if (L > R) {
                left.delMax();
            }
            else {
                right.delMin();
            }
        }

    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我是文文,第06天打卡 学习心得:昨天作业写的五个选品,突然就觉得很难结合实体店产品和服务来切入,因为一直局限于做...
    文文_c6ac阅读 119评论 0 1
  • 我是一个零零后的小姑娘,也是一个土生土长的农村妹子,对于我来说,学习真的好重要,就算我真的不喜欢埋头于书籍中,也要...
    易懂双宸阅读 365评论 1 3
  • 睡前拉着儿子“来跟妈妈聊一聊”,“我知道你要聊什么~”敏感如他。 早上在便利店买了三明治做早餐,到...
    阳光一直明媚阅读 170评论 0 0
  • 不要让战术上勤奋掩盖战略上的懒惰。很多人都生活在“让自己看上去很努力”的状态中,比如说,很多人认为“做事情”很重要...
    85后栗子阅读 788评论 0 0