zoukankan      html  css  js  c++  java
  • 数据流中的中位数-剑指Offer

    数据流中的中位数

    题目描述

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

    思路

    1. 我们可以用数组存,每次取中位数时需要排序
    2. 我们也可以用平衡二叉树存,不过构造树的过程很复杂
    3. 我们也可以用大小堆存,不过也不简单
    4. 最后我选择用java里现成的ArrayList存,用Collections.sort()方法排序

    代码

    import java.util.ArrayList;
    import java.util.Collections;
    public class Solution {
    
        ArrayList<Integer> numList = null;
    	Solution() {
    		numList = new ArrayList<Integer>();
    	}
    	public void Insert(Integer num) {
    	    numList.add(num);
        }
    
        public Double GetMedian() {
        	Collections.sort(numList);
        	int length = numList.size();
        	int temp = length / 2;
        	if (length % 2 == 0) {
        		return (double)(numList.get(temp) + numList.get(temp - 1)) / 2;
        	} else {
        		return (double)(numList.get(temp));
        	}
        }
    
    
    }
  • 相关阅读:
    使用 Sentry集中处理错误
    laravel实现多对多的分析
    windows下phpstorm的快捷键
    npm 升级
    squid----正向代理
    nginx----配置优化
    负载均衡----nginx
    负载均衡----HAproxy
    负载均衡----LVS
    mysql-8.0.12读写分离
  • 原文地址:https://www.cnblogs.com/rosending/p/5722458.html
Copyright © 2011-2022 走看看