lintcode(81)数据流中位数

Description:

数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。

中位数的定义:

  • 中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
  • 比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。

Explanation:

持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]

持续进入数组的数的列表为:[4, 5, 1, 3, 2, 6, 0],则返回 [4, 4, 4, 3, 3, 3, 3]

持续进入数组的数的列表为:[2, 20, 100],则返回[2, 2, 20]

Solution:

Set up arraylist record to dynamically  add integer element, and then sort the record. The (i/2)th integer in the arraylist record is the current median.

public class Solution {
    /**
     * @param nums: A list of integers.
     * @return: the median of numbers
     */
    public int[] medianII(int[] nums) {
        // write your code here
        
        int len = nums.length;
        int[] result = new int[len];
        
        ArrayList<Integer> record = new ArrayList<Integer>();
        for(int i = 0;i<len;i++){
            record.add(nums[i]);
            Collections.sort(record);
            int count = i/2;
            result[i] = record.get(count);
        }
        
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值