Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples: [2,3,4] , the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far.

For example:

addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2

Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases.

Solution

public class MedianFinder {
   PriorityQueue<Integer> maxHeap;
    PriorityQueue<Integer> minHeap;

    public MedianFinder() {
        maxHeap = new PriorityQueue<>((a, b) -> {
            return -a.compareTo(b);
        });
        minHeap = new PriorityQueue<>((a, b) -> {
            return a.compareTo(b);
        });
    }

    // Adds a number into the data structure.
    public void addNum(int num) {
        if (maxHeap.isEmpty()) {
            maxHeap.add(num);
            return;
        }

        int m = maxHeap.peek();

        if (minHeap.isEmpty()) {
            if (num < m) {
                minHeap.add(maxHeap.poll());
                maxHeap.add(num);
            } else {
                minHeap.add(num);
            }
            return;
        }


        int n = minHeap.peek();

        if (num <= m) {
            if (maxHeap.size() > minHeap.size()) {
                maxHeap.poll();
                maxHeap.add(num);
                minHeap.add(m);
            } else {
                maxHeap.add(num);
            }
        } else if (num <= n) {
            if (maxHeap.size() > minHeap.size()) {
                minHeap.add(num);
            } else {
                maxHeap.add(num);
            }
        } else {
            if (maxHeap.size() > minHeap.size()) {
                minHeap.add(num);
            } else {
                maxHeap.add(minHeap.poll());
                minHeap.add(num);
            }
        }

    }

    // Returns the median of current data stream
    public double findMedian() {
        if (maxHeap.size() > minHeap.size()) {
            return maxHeap.peek();
        } else {
            int m = maxHeap.peek();
            int n = minHeap.peek();
            return (m + n) / 2.0;
        }
    }

};

results matching ""

    No results matching ""