Skip to content

Commit 5db2af0

Browse files
committedJan 18, 2025
Add solution #295
1 parent 2edd67d commit 5db2af0

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@
173173
278|[First Bad Version](./0278-first-bad-version.js)|Medium|
174174
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
175175
290|[Word Pattern](./0290-word-pattern.js)|Easy|
176+
295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard|
176177
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
177178
326|[Power of Three](./0326-power-of-three.js)|Easy|
178179
328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)
Please sign in to comment.