数据流中的中位数(无序)

【题目】

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

方法1:

找中位数也可以用快排分治的思想。

具体如下:
任意挑一个元素,以改元素为支点,划分集合为两部分,如果左侧集合长度恰为 (n-1)/2,那么支点恰为中位数。
如果左侧长度<(n-1)/2, 那么中位点在右侧,
反之,中位数在左侧。 进入相应的一侧继续寻找中位点。

    public static void main(String[] args) throws Exception {
        int[] arr = {2,1,3,5,4,6,8,7};
        int res = GetMidNumNoSort1(arr,arr.length);
        System.out.println(res);//4


}
    //快排核心
    public static int partion(int[] arr,int start,int end){
        int left=start;
        int right=end;
        int tmp = arr[left];
        while(left<right){
            while(left<right && arr[right]>=tmp){
                right--;
            }
            arr[left]=arr[right];
            while(left<right && arr[left]<=tmp){
                left++;
            }
            arr[right]=arr[left];
        }
        arr[left] = tmp;
        return left;
    }
    //无序数组找中位数
    public static int GetMidNumNoSort1(int[] arr,int size)
    {
        if(arr == null || arr.length ==0 ){
            return 0;
        }
        int start =0;
        int end=size-1;
        int mid=(size-1)/2;
        int div=partion(arr,start,end);
        while(div!=mid){
            if(div<mid){//在右半区找
                div=partion(arr,div+1,end);
            }else{//在左半区找
                div=partion(arr,start,div-1);
            }
        }
        return arr[mid];
    }

方法2:

链接:https://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1
来源:牛客网

private int count = 0;
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
//PriorityQueue默认是小顶堆
private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() {
    @Override //初始容量是11
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
});

public void Insert(Integer num) {
    if ((count & 1) == 1) {//当数据总数为偶数时,新加入的元素,应当进入小根堆
        //(注意不是直接进入小根堆,而是经大根堆筛选后取大根堆中最大元素进入小根堆)
        //1.新加入的元素先入到大根堆,由大根堆筛选出堆中最大的元素
        maxHeap.offer(num);
        int filteredMaxNum = maxHeap.poll();
        //2.筛选后的【大根堆中的最大元素】进入小根堆
        minHeap.offer(filteredMaxNum);
    } else {//当数据总数为奇数时,新加入的元素,应当进入大根堆
        //(注意不是直接进入大根堆,而是经小根堆筛选后取小根堆中最大元素进入大根堆)
        //1.新加入的元素先入到小根堆,由小根堆筛选出堆中最小的元素
        minHeap.offer(num);
        int filteredMinNum = minHeap.poll();
        //2.筛选后的【小根堆中的最小元素】进入大根堆
        maxHeap.offer(filteredMinNum);
    }
    count++;
}

public Double GetMedian() {
    if ((count &1) == 1) {//偶数个数
        return new Double((minHeap.peek() + maxHeap.peek())) / 2;
    } else {
        return new Double(minHeap.peek());
    }
}

去掉注释

import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
    private int count=0;
    private PriorityQueue<Integer> minHeap=new PriorityQueue<>();
    private PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(11,
                                      new Comparator<Integer>(){
        public int compare(Integer o1,Integer o2){
            return o2-o1;
        }
    });
    public void Insert(Integer num) {
        if((count&1)==0){
            maxHeap.offer(num);
            int max=maxHeap.poll();
            minHeap.offer(max);
        }else{
            minHeap.offer(num);
            int min=minHeap.poll();
            maxHeap.offer(min);
        }
        count++;
    }

    public Double GetMedian() {
        if((count&1)==0) {
            return new Double((minHeap.peek()+maxHeap.peek()))/2;
        }else{
            return new Double(minHeap.peek());
        }
    }


}

【理解】

1.第1个数放大顶堆,第2个数放小顶堆,第3个数放大顶堆…
即:奇数个数放大顶堆,偶数个数放小顶堆,
一共奇数个数时,中位数=小顶堆堆顶(中位数下标为偶数)

2.大小顶堆会自动排序,大顶堆始终是堆中最大数,小顶堆始终是堆中最小数…
即:一共偶数个数时,中位数=(大顶堆堆顶+小顶堆堆顶)/2

3.最终,前一半较小的数在大顶堆,后一半较大的数在小顶堆

另一种代码:

解题思路:

通过最大堆、最小堆来实现实时中位数的获取。
最大堆中存放比最小堆小的元素。
如果最大堆的对头元素大于最小堆,则进行交换。
偶数下标的元素存入最小堆,奇数下标的元素存入最大堆。
public class Middle {
    public int[] getMiddle(int[] A, int n) {
        // write code here
        int[] res = new int[A.length];

        // 构造最大堆
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        };
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(n, comparator);
        // 构造最小堆
        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(n);

        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                // 存入最小堆前判断当前元素是否小于最大堆的堆顶元素
                if (!maxHeap.isEmpty() && A[i] < maxHeap.peek()) {
                    minHeap.offer(maxHeap.poll());
                    maxHeap.offer(A[i]);
                } else {
                    minHeap.offer(A[i]);
                }
                res[i] = minHeap.peek();
            } else {
                // 存入最大堆之前判断当前元素是否大于最小堆的堆顶元素
                if (!minHeap.isEmpty() && A[i] > minHeap.peek()) {
                    maxHeap.offer(minHeap.poll());
                    minHeap.offer(A[i]);
                } else {
                    maxHeap.offer(A[i]);
                }
                res[i] = maxHeap.peek();
            }
        }

        return res;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值