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:
add(1) add(2) findMedian() -> 1.5 add(3) findMedian() -> 2
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Solution:
1 public class MedianFinder { 2 // small part, max heap 3 PriorityQueue<Integer> small = new PriorityQueue<Integer>((a, b) -> (b - a)); 4 5 // large part, min heap, contains median if odd number of numbers are added. 6 PriorityQueue<Integer> large = new PriorityQueue<Integer>(); 7 8 // Adds a number into the data structure. 9 public void addNum(int num) { 10 if (large.isEmpty()) { 11 large.add(num); 12 return; 13 } 14 15 // total number is even 16 if (small.size()==large.size()) { 17 if (num >= small.peek()) { 18 // add it to large. 19 large.add(num); 20 } else { 21 small.add(num); 22 large.add(small.poll()); 23 } 24 } else { 25 if (num > large.peek()) { 26 large.add(num); 27 small.add(large.poll()); 28 } else { 29 small.add(num); 30 } 31 } 32 } 33 34 // Returns the median of current data stream 35 public double findMedian() { 36 if (small.size()==large.size()){ 37 return (double) (small.peek()+large.peek())/2; 38 } else { 39 return (double) large.peek(); 40 } 41 } 42 43 }; 44 45 // Your MedianFinder object will be instantiated and called as such: 46 // MedianFinder mf = new MedianFinder(); 47 // mf.addNum(1); 48 // mf.findMedian();