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 is3
[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.
publicclassMedianFinder {PriorityQueue<Integer> minHeap;PriorityQueue<Integer> maxHeap; /** initialize your data structure here. */publicMedianFinder() { minHeap =newPriorityQueue<>(); maxHeap =newPriorityQueue<>(10,Collections.reverseOrder()); }// maxHeap has 1 more element than minHeappublicvoidaddNum(int num) {if (minHeap.size() ==maxHeap.size()) {if ((!minHeap.isEmpty()) && num >minHeap.peek()) {maxHeap.offer(minHeap.poll());minHeap.offer(num); } else {maxHeap.offer(num); } } else {if (num <maxHeap.peek()) {minHeap.offer(maxHeap.poll());maxHeap.offer(num); } else {minHeap.offer(num); } } }publicdoublefindMedian() {int curSize =maxHeap.size() +minHeap.size();if (curSize %2==0) {return (maxHeap.peek() +minHeap.peek()) /2.0; } else {returnmaxHeap.peek() *1.0; } }}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
L81 Data Stream Median
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 is2. IfA=[1,19], median is1.
publicint[] medianII(int[] nums) {if (nums ==null||nums.length==0) {returnnull; }int[] res =newint[nums.length];PriorityQueue<Integer> minHeap =newPriorityQueue<>();// store larger elements PriorityQueue<Integer> maxHeap = new PriorityQueue<>(nums.length, Collections.reverseOrder());// store smaller elements
for (int i =0; i <nums.length; i++) {int cur = nums[i];if (maxHeap.isEmpty()) {maxHeap.offer(cur); } elseif (minHeap.isEmpty()) {maxHeap.offer(cur);minHeap.offer(maxHeap.poll()); } elseif (cur >minHeap.peek()) {minHeap.offer(cur); } else {maxHeap.offer(cur); }if (maxHeap.size() >minHeap.size() +1) {minHeap.offer(maxHeap.poll()); } elseif (minHeap.size() >maxHeap.size()) {maxHeap.offer(minHeap.poll()); }/* if need to calculate (mid + mid + 1) / 2 version. you will add the (min.peek + max.peek) / 2 when total size is even. return max.peek when total size is off*/ res[i] =maxHeap.peek(); }return res;}