Skip to content

Commit c14d795

Browse files
committed
MedianFinder2
1 parent 341c223 commit c14d795

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

find-median-from-data-stream/test.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
import { assertEquals } from "../deps.ts";
2-
import MedianFinder from "./index.ts";
2+
import MedianFinder1 from "./index.ts";
3+
import MedianFinder2 from "./MedianFinder.ts";
34

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();
616

717
medianFinder.addNum(1);
818
medianFinder.addNum(2);

0 commit comments

Comments
 (0)