|
| 1 | +/** |
| 2 | + * 295. Find Median from Data Stream |
| 3 | + * https://leetcode.com/problems/find-median-from-data-stream/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * The median is the middle value in an ordered integer list. If the size of the list is |
| 7 | + * even, there is no middle value, and the median is the mean of the two middle values. |
| 8 | + * |
| 9 | + * - For example, for arr = [2,3,4], the median is 3. |
| 10 | + * - For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. |
| 11 | + * |
| 12 | + * Implement the MedianFinder class: |
| 13 | + * - MedianFinder() initializes the MedianFinder object. |
| 14 | + * - void addNum(int num) adds the integer num from the data stream to the data structure. |
| 15 | + * - double findMedian() returns the median of all elements so far. Answers within 10-5 of |
| 16 | + * the actual answer will be accepted. |
| 17 | + */ |
| 18 | + |
| 19 | + |
| 20 | +var MedianFinder = function() { |
| 21 | + this.minHeap = new MinPriorityQueue(); |
| 22 | + this.maxHeap = new MaxPriorityQueue(); |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} num |
| 27 | + * @return {void} |
| 28 | + */ |
| 29 | +MedianFinder.prototype.addNum = function(num) { |
| 30 | + this.minHeap.enqueue(num); |
| 31 | + this.maxHeap.enqueue(this.minHeap.dequeue().element); |
| 32 | + if (this.minHeap.size() < this.maxHeap.size()) { |
| 33 | + this.minHeap.enqueue(this.maxHeap.dequeue().element); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * @return {number} |
| 39 | + */ |
| 40 | +MedianFinder.prototype.findMedian = function() { |
| 41 | + return this.minHeap.size() > this.maxHeap.size() |
| 42 | + ? this.minHeap.front().element |
| 43 | + : (this.minHeap.front().element + this.maxHeap.front().element) / 2; |
| 44 | +}; |
0 commit comments