File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ class MedianFinder {
2+ private left : PriorityQueue < number > ;
3+ private right : PriorityQueue < number > ;
4+
5+ constructor ( ) {
6+ this . left = new PriorityQueue < number > ( ( a , b ) => b - a ) ; // 최대 힙
7+ this . right = new PriorityQueue < number > ( ( a , b ) => a - b ) ; // 최소 힙
8+ }
9+
10+ addNum ( num : number ) : void {
11+ if ( this . left . isEmpty ( ) || num <= this . left . front ( ) ) {
12+ this . left . enqueue ( num ) ;
13+ } else {
14+ this . right . enqueue ( num ) ;
15+ }
16+
17+ if ( this . left . size ( ) > this . right . size ( ) + 1 ) {
18+ this . right . enqueue ( this . left . dequeue ( ) ) ;
19+ }
20+
21+ if ( this . right . size ( ) > this . left . size ( ) ) {
22+ this . left . enqueue ( this . right . dequeue ( ) ) ;
23+ }
24+
25+ if ( ! this . right . isEmpty ( ) && this . left . front ( ) > this . right . front ( ) ) {
26+ const maxValue = this . left . dequeue ( ) ;
27+
28+ this . right . enqueue ( maxValue ) ;
29+ }
30+ }
31+
32+ findMedian ( ) : number {
33+ let result = 0 ;
34+
35+ if ( this . left . size ( ) === this . right . size ( ) ) {
36+ result = ( this . left . front ( ) + this . right . front ( ) ) / 2 ;
37+ } else if ( this . left . size ( ) === this . right . size ( ) + 1 ) {
38+ result = this . left . front ( ) ;
39+ }
40+
41+ return result ;
42+ }
43+ }
44+
45+ /**
46+ * Your MedianFinder object will be instantiated and called as such:
47+ * var obj = new MedianFinder()
48+ * obj.addNum(num)
49+ * var param_2 = obj.findMedian()
50+ */
You can’t perform that action at this time.
0 commit comments