lintcode(81)数据流中位数

来源:互联网 发布:java线程安全集合类 编辑:程序博客网 时间:2024/06/07 09:33

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;    }}


原创粉丝点击