树8:如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

方法1:使用动态数组做。

!回顾 arrayList 、Linklist array区别:

Array:静态数组

arrayList:基于动态数组,参见https://www.cnblogs.com/battlecry/p/9374497.html

Linklist:基于动态链表,参见https://blog.csdn.net/qedgbmwyz/article/details/80108618

arrayList相比Linklist更适合查询和读取,因为LinkedList要移动指针。Linklist相比arrayList更适合增删操作,因为arrayList要移动大量数据。

思路:此题是读取数据流并进行查询操作,用ArrayList更合适。

!ArrayList常见的方法

array.add(object);//添加一个元素
array.get(index);//取出集合中的元素,在get方法的参数中,写入索引。
array.size();//返回集合的长度,也就是存储元素的个数。
array.remove();//移除一个元素
 

代码:

import java.util.*;
public class Solution {
    List<Double>list=new ArrayList<Double>();
    public void Insert(Integer num) {
        list.add(Double.valueOf(num));//返回给定参数num的原生Double对象值
        Collections.sort(list);//ArrayList的排序
    }

    public Double GetMedian() {
        double res=0;
        int len=list.size();
        if(len==1)res=list.get(0);
        else if(len%2==0){
            int tmp=len/2;
            res=(list.get(tmp)+list.get(tmp-1))/2.0;
        }else{
            int tmp=len/2;
            res=list.get(tmp);
        }
        return res;
    }
}

 

方法2:大顶堆小顶堆

猜你喜欢

转载自www.cnblogs.com/xuechengmeigui/p/12664144.html
今日推荐