Data Stream Median

来源:互联网 发布:查询域名注册信息 编辑:程序博客网 时间:2024/05/17 12:19

Numbers keep coming, return the median of numbers at every time a new number added.

Clarification

What's the definition of Median?
- Median is the number that in the middle of a sorted array. If there are n numbers in a sorted array A, the median is A[(n - 1) / 2]. For example, if A=[1,2,3], median is 2. If A=[1,19], median is 1.

Example

For numbers coming list: [1, 2, 3, 4, 5], return [1, 1, 2, 2, 3].

For numbers coming list: [4, 5, 1, 3, 2, 6, 0], return [4, 4, 4, 3, 3, 3, 3].

For numbers coming list: [2, 20, 100], return [2, 2, 20].


java

这个方法超时,但却是最为直接想到的一个方法

public class Solution {    /*     * @param nums: A list of integers     * @return: the median of numbers     */    public int[] medianII(int[] nums) {        // write your code here        Queue<Integer> queue = new PriorityQueue<>();        List<Integer> list = new ArrayList<>();        Queue<Integer> temp;        int val = 0;        int cache = 0;        for (int i = 0; i < nums.length; i++) {            queue.offer(nums[i]);            val = queue.size();            temp = new PriorityQueue<Integer>(queue);            int j = (val - 1) / 2;            while(j > 0) {                temp.poll();                j--;            }            list.add(temp.poll());        }        int[] arr = new int[list.size()];        for (int i = 0; i < list.size(); i++) {            arr[i] = list.get(i);        }        return arr;    }}