Lintcode - MedianII

Numbers keep coming, return the median of numbers at every time a new number added.

Example

For numbers coming list: [1, 2, 3, 4, 5], return [1, 1, 2, 2, 3]

For numbers coming list: [4, 5, 1, 3, 2, 6, 0], return [4, 4, 4, 3, 3, 3, 3]

For numbers coming list: [2, 20, 100], return [2, 2, 20]

Challenge

O(nlogn) time

解题思路:

一个maxheap,一个minheap,maxheap用来保存median以及比median小的堆,maxheap用来保存比median大的堆

几种情况:

1.两个heap size相等,如果新数字比minheap的最小值小,毫无疑问加入maxheap;否则把他放到minheap,并从minheap pop一个数字到maxheap

2.maxheap size大,如果新数字比maxheap的最大值小,则需要从maxheap pop出一个数到minheap,然后把新数字加到maxheap

不管那种情况,median都在maxheap的头部

     */
    public int[] medianII(int[] nums) {
        Queue<Integer> smallQueue = new PriorityQueue<Integer>(nums.length / 2 + 1, 
                new Comparator<Integer>() {
                    @Override
                    public int compare(Integer a, Integer b) {
                        return a.compareTo(b) * -1;
                    }
                });
        Queue<Integer> bigQueue = new PriorityQueue<Integer>(nums.length / 2 + 1, 
                new Comparator<Integer>() {
                    @Override
                    public int compare(Integer a, Integer b) {
                        return a.compareTo(b);
                    }
                });

        int[] result = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            if (smallQueue.size() == bigQueue.size()) {
                if (smallQueue.size() == 0) {
                    smallQueue.offer(nums[i]);
                } else if (nums[i] <= bigQueue.peek()) {
                    smallQueue.offer(nums[i]);
                } else {
                    smallQueue.offer(bigQueue.poll());
                    bigQueue.offer(nums[i]);
                }
            } else {
                if (nums[i] <= smallQueue.peek()) {
                    bigQueue.offer(smallQueue.poll());
                    smallQueue.offer(nums[i]);
                } else {
                    bigQueue.offer(nums[i]);
                }
            }
            result[i] = smallQueue.peek();
        }
        return result;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值