|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=295 lang=java |
| 3 | + * |
| 4 | + * [295] Find Median from Data Stream |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/find-median-from-data-stream/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Hard (34.96%) |
| 10 | + * Total Accepted: 101.2K |
| 11 | + * Total Submissions: 282.3K |
| 12 | + * Testcase Example: '["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"]\n[[],[1],[2],[],[3],[]]' |
| 13 | + * |
| 14 | + * Median is the middle value in an ordered integer list. If the size of the |
| 15 | + * list is even, there is no middle value. So the median is the mean of the two |
| 16 | + * middle value. |
| 17 | + * For example, |
| 18 | + * |
| 19 | + * [2,3,4], the median is 3 |
| 20 | + * |
| 21 | + * [2,3], the median is (2 + 3) / 2 = 2.5 |
| 22 | + * |
| 23 | + * Design a data structure that supports the following two operations: |
| 24 | + * |
| 25 | + * |
| 26 | + * void addNum(int num) - Add a integer number from the data stream to the data |
| 27 | + * structure. |
| 28 | + * double findMedian() - Return the median of all elements so far. |
| 29 | + * |
| 30 | + * |
| 31 | + * |
| 32 | + * |
| 33 | + * Example: |
| 34 | + * |
| 35 | + * |
| 36 | + * addNum(1) |
| 37 | + * addNum(2) |
| 38 | + * findMedian() -> 1.5 |
| 39 | + * addNum(3) |
| 40 | + * findMedian() -> 2 |
| 41 | + * |
| 42 | + * |
| 43 | + * |
| 44 | + * |
| 45 | + * Follow up: |
| 46 | + * |
| 47 | + * |
| 48 | + * If all integer numbers from the stream are between 0 and 100, how would you |
| 49 | + * optimize it? |
| 50 | + * If 99% of all integer numbers from the stream are between 0 and 100, how |
| 51 | + * would you optimize it? |
| 52 | + * |
| 53 | + * |
| 54 | + */ |
| 55 | +class MedianFinder { |
| 56 | + |
| 57 | + public PriorityQueue<Integer> minheap, maxheap; |
| 58 | + |
| 59 | + /** initialize your data structure here. */ |
| 60 | + public MedianFinder() { |
| 61 | + minheap = new PriorityQueue<Integer>(); |
| 62 | + maxheap = new PriorityQueue<Integer>(Collections.reverseOrder()); |
| 63 | + } |
| 64 | + |
| 65 | + public void addNum(int num) { |
| 66 | + maxheap.add(num); |
| 67 | + minheap.add(maxheap.poll()); |
| 68 | + if (maxheap.size() < minheap.size()) { |
| 69 | + maxheap.add(minheap.poll()); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public double findMedian() { |
| 74 | + if (minheap.size() == maxheap.size()) { |
| 75 | + return (minheap.peek() + maxheap.peek()) * 0.5; |
| 76 | + } else { |
| 77 | + return maxheap.peek(); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Your MedianFinder object will be instantiated and called as such: |
| 84 | + * MedianFinder obj = new MedianFinder(); |
| 85 | + * obj.addNum(num); |
| 86 | + * double param_2 = obj.findMedian(); |
| 87 | + */ |
| 88 | + |
0 commit comments