File tree Expand file tree Collapse file tree 2 files changed +47
-3
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 2 files changed +47
-3
lines changed Original file line number Diff line number Diff line change
1
+ import { Heap } from "../deps.ts" ;
2
+
3
+ export default class MedianFinder {
4
+ #min: Heap < number > ;
5
+ #max: Heap < number > ;
6
+ constructor ( ) {
7
+ this . #min = new Heap ( ( a , b ) => a - b ) ;
8
+ this . #max = new Heap ( ( a , b ) => b - a ) ;
9
+ }
10
+ addNum ( num : number ) {
11
+ const max = this . #max,
12
+ min = this . #min;
13
+ const m = max . size ( ) ,
14
+ n = min . size ( ) ;
15
+ if ( m == n ) {
16
+ // 两个堆数目相等:m=n
17
+ min . insert ( num ) ;
18
+ max . insert ( min . pop ( ) ) ;
19
+ } else {
20
+ // 两个堆数目不相等:m=n+1
21
+ max . insert ( num ) ;
22
+ min . insert ( max . pop ( ) ) ;
23
+ }
24
+ }
25
+ findMedian ( ) {
26
+ const max = this . #max,
27
+ min = this . #min;
28
+ if ( max . size ( ) === min . size ( ) ) {
29
+ return ( max . top ( ) + min . top ( ) ) / 2 ;
30
+ } else {
31
+ return max . top ( ) ;
32
+ }
33
+ }
34
+ }
Original file line number Diff line number Diff line change 1
1
import { assertEquals } from "../deps.ts" ;
2
- import MedianFinder from "./index.ts" ;
2
+ import MedianFinder1 from "./index.ts" ;
3
+ import MedianFinder2 from "./MedianFinder.ts" ;
3
4
4
- Deno . test ( "find-median-from-data-stream" , ( ) => {
5
- const medianFinder = new MedianFinder ( ) ;
5
+ Deno . test ( "find-median-from-data-stream-1" , ( ) => {
6
+ const medianFinder = new MedianFinder1 ( ) ;
7
+
8
+ medianFinder . addNum ( 1 ) ;
9
+ medianFinder . addNum ( 2 ) ;
10
+ assertEquals ( medianFinder . findMedian ( ) , 1.5 ) ;
11
+ medianFinder . addNum ( 3 ) ;
12
+ assertEquals ( medianFinder . findMedian ( ) , 2 ) ;
13
+ } ) ;
14
+ Deno . test ( "find-median-from-data-stream-2" , ( ) => {
15
+ const medianFinder = new MedianFinder2 ( ) ;
6
16
7
17
medianFinder . addNum ( 1 ) ;
8
18
medianFinder . addNum ( 2 ) ;
You can’t perform that action at this time.
0 commit comments