We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1426c17 commit a9289c9Copy full SHA for a9289c9
find-median-from-data-stream/sora0319.java
@@ -0,0 +1,26 @@
1
+public class MedianFinder {
2
+ private PriorityQueue<Integer> maxHeap;
3
+ private PriorityQueue<Integer> minHeap;
4
+
5
+ public MedianFinder() {
6
+ maxHeap = new PriorityQueue<>(Collections.reverseOrder());
7
+ minHeap = new PriorityQueue<>();
8
+ }
9
10
+ public void addNum(int num) {
11
+ maxHeap.offer(num);
12
+ minHeap.offer(maxHeap.poll());
13
14
+ if (minHeap.size() > maxHeap.size()) {
15
+ maxHeap.offer(minHeap.poll());
16
17
18
19
+ public double findMedian() {
20
+ if (maxHeap.size() > minHeap.size()) {
21
+ return maxHeap.peek();
22
+ } else {
23
+ return (maxHeap.peek() + minHeap.peek()) / 2.0;
24
25
26
+}
0 commit comments