LeetCode – Find Median from Data Stream (Java)
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.
Analysis
First of all, it seems that the best time complexity we can get for this problem is O(log(n)) of add() and O(1) of getMedian(). This data structure seems highly likely to be a tree.
We can use heap to solve this problem. In Java, the PriorityQueue
class is a priority heap. We can use two heaps to store the lower half and the higher half of the data stream. The size of the two heaps differs at most 1.
class MedianFinder { PriorityQueue<Integer> minHeap = null; PriorityQueue<Integer> maxHeap = null; /** initialize your data structure here. */ public MedianFinder() { minHeap = new PriorityQueue<>(); maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); } public void addNum(int num) { minHeap.offer(num); maxHeap.offer(minHeap.poll()); if(minHeap.size()<maxHeap.size()){ minHeap.offer(maxHeap.poll()); } } public double findMedian() { if(minHeap.size() > maxHeap.size()){ return minHeap.peek(); }else { return (minHeap.peek()+maxHeap.peek())/2.0; } } } |
<pre><code> String foo = "bar"; </code></pre>
-
Gautam Tyagi
-
Mathias Haugsbø
-
Arif Azim
-
Anju rawat
-
Deepak Singh
-
Sonali Vishwakarma
-
anil
-
Utkarsh Tiwari