Skip to content

Commit 9202c79

Browse files
committed
feat: find-median-from-data-stream
1 parent 1eea720 commit 9202c79

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/find-median-from-data-stream/">week13-4. find-median-from-data-stream</a>
3+
* <li>Description: Implement the MedianFinder class</li>
4+
* <li>Topics: Two Pointers, Design, Sorting, Heap (Priority Queue), Data Stream</li>
5+
* <li>Time Complexity: O(logN), Runtime 99ms </li>
6+
* <li>Space Complexity: O(N), Memory 63.68MB </li>
7+
*/
8+
9+
class MedianFinder {
10+
PriorityQueue<Integer> head;
11+
PriorityQueue<Integer> tail;
12+
13+
public MedianFinder() {
14+
head = new PriorityQueue<>(Comparator.reverseOrder());
15+
tail = new PriorityQueue<>();
16+
}
17+
18+
public void addNum(int num) {
19+
if(head.isEmpty() || num <= head.peek()) {
20+
head.add(num);
21+
} else {
22+
tail.add(num);
23+
}
24+
25+
if (head.size() > tail.size() + 1) {
26+
tail.add(head.poll());
27+
} else if (head.size() < tail.size()) {
28+
head.add(tail.poll());
29+
}
30+
}
31+
32+
public double findMedian() {
33+
if(head.size() == tail.size()){
34+
return ((double)head.peek() + tail.peek()) / 2;
35+
}
36+
return head.peek();
37+
}
38+
}
39+
40+
/**
41+
* Your MedianFinder object will be instantiated and called as such:
42+
* MedianFinder obj = new MedianFinder();
43+
* obj.addNum(num);
44+
* double param_2 = obj.findMedian();
45+
*/

0 commit comments

Comments
 (0)