Thursday, July 30, 2015

Data Stream Median

Data Stream Median

24%
Accepted
Numbers keep coming, return the median of numbers at every time a new number added.
Have you met this question in a real interview? 
Yes
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].
Challenge
Total run time in O(nlogn).
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, if A=[1,2,3], median is 2. If A=[1,19], median is 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 nums;
        int[] medians = new int[nums.length];
        int size = 10;
        Queue<Integer> minHeap = new PriorityQueue<Integer>(size, new Comparator<Integer>(){
            public int compare(Integer a, Integer b){
                return b - a;
            }
        });
        
        Queue<Integer> maxHeap = new PriorityQueue<Integer>(size, new Comparator<Integer>(){
            public int compare(Integer a, Integer b){
                return a - b;
            }
        });
        for(int i = 0; i < nums.length; i++){
            if(minHeap.size() > maxHeap.size()){
                if(nums[i] > minHeap.peek()){
                    maxHeap.offer(nums[i]);
                } else {
                    maxHeap.offer(minHeap.poll());
                    minHeap.offer(nums[i]);
                }
            } else {
                if(minHeap.isEmpty() || nums[i] <= maxHeap.peek()){
                    minHeap.offer(nums[i]);
                } else {
                    minHeap.offer(maxHeap.poll());
                    maxHeap.offer(nums[i]);
                }
            }
            medians[i] = minHeap.peek(); 
        }
        return medians;
    }
}


No comments:

Post a Comment