Description

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 isA[(n - 1) / 2]. For example, ifA=[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].

Solution

两个Priority Queue,根据min.size == max.size || max.size+1来判断新来的num应该往哪放,medium要不要改。
Priority Queue的top是最小值的数。min heap要poll出最大值,而max heap要poll出最小值,所以在min heap存负数,拿出来和放进去的时候都要取负
注意Priority Queue的长度初始化位length/2+1

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: the median of numbers
     */
    public int[] medianII(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int[] result = new int[nums.length];
        PriorityQueue<Integer> min = new PriorityQueue<Integer>(nums.length/2 + 1);
        PriorityQueue<Integer> max = new PriorityQueue<Integer>(nums.length/2 + 1);
        int medium = nums[0];
        result[0] = medium;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > medium) {
                if (min.size() == max.size()) {
                    max.offer(nums[i]);
                } else {
                    min.offer(-medium);
                    max.offer(nums[i]);
                    medium = max.poll();
                }
            } else {
                if (min.size() < max.size()) {
                    min.offer(-nums[i]);
                } else {
                    max.offer(medium);
                    min.offer(-nums[i]);
                    medium = -min.poll();
                }
            }

            result[i] = medium;
        }

        return result;
    }
}

results matching ""

    No results matching ""