@@ -48,8 +48,8 @@ public static class Solution2 {
48
48
public static class MedianFinder {
49
49
/**
50
50
* credit: https://discuss.leetcode.com/topic/27521/short-simple-java-c-python-o-log-n-o-1
51
- * The idea is for sure to use two heaps, one is max heap, one is min heap, we always let the max heap be one element
52
- * bigger than min heap if the total number of elements is not even.
51
+ * The idea is for sure to use two heaps, one is max heap, one is min heap, we always let the max heap have one more element
52
+ * than min heap if the total number of elements is not even.
53
53
* we could always get the median in O(1) time.
54
54
* 1. use Long type to avoid overflow
55
55
* 2. negate the numbers for small heap to save the effort for writing a reverse comparator, brilliant!
@@ -85,4 +85,41 @@ public double findMedian() {
85
85
86
86
}
87
87
}
88
+
89
+ public static class Solution3 {
90
+ public static class MedianFinder {
91
+ /**
92
+ * The same as Solution2, but not using negation for minHeap.
93
+ */
94
+
95
+ private Queue <Long > maxHeap ;
96
+ private Queue <Long > minHeap ;
97
+
98
+ /**
99
+ * initialize your data structure here.
100
+ */
101
+ public MedianFinder () {
102
+ maxHeap = new PriorityQueue <>();
103
+ minHeap = new PriorityQueue <>((a , b ) -> (int ) (b - a ));
104
+ }
105
+
106
+ // Adds a number into the data structure.
107
+ public void addNum (int num ) {
108
+ maxHeap .offer ((long ) num );
109
+ minHeap .offer (maxHeap .poll ());
110
+ if (maxHeap .size () < minHeap .size ()) {
111
+ maxHeap .offer (minHeap .poll ());
112
+ }
113
+ }
114
+
115
+ // Returns the median of current data stream
116
+ public double findMedian () {
117
+ if (maxHeap .size () > minHeap .size ()) {
118
+ return maxHeap .peek ();
119
+ }
120
+ return (maxHeap .peek () + minHeap .peek ()) / 2.0 ;
121
+ }
122
+
123
+ }
124
+ }
88
125
}
0 commit comments