|
1 | 1 | class MedianFinder {
|
2 |
| - private array: number[]; |
| 2 | + public minHeap; |
| 3 | + public maxHeap; |
3 | 4 |
|
4 | 5 | constructor() {
|
5 |
| - this.array = []; |
| 6 | + this.minHeap = new MinPriorityQueue(); |
| 7 | + this.maxHeap = new MaxPriorityQueue(); |
6 | 8 | }
|
7 | 9 |
|
8 | 10 | addNum(num: number): void {
|
9 |
| - if (this.array.length === 0) { |
10 |
| - this.array.push(num); |
11 |
| - return; |
12 |
| - } |
13 |
| - |
14 |
| - let left = 0; |
15 |
| - let right = this.array.length - 1; |
16 |
| - |
17 |
| - while (left <= right) { |
18 |
| - const mid = Math.floor((left + right) / 2); |
19 |
| - |
20 |
| - if (this.array[mid] === num) { |
21 |
| - this.array.splice(mid, 0, num); |
22 |
| - return; |
23 |
| - } |
| 11 | + this.getHeap(num).enqueue(num); |
| 12 | + this.rebalance(); |
| 13 | + } |
24 | 14 |
|
25 |
| - if (this.array[mid] > num) { |
26 |
| - right = mid - 1; |
27 |
| - } else { |
28 |
| - left = mid + 1; |
29 |
| - } |
| 15 | + findMedian(): number { |
| 16 | + if (this.minHeap.size() === this.maxHeap.size()) { |
| 17 | + return (this.minHeap.front().element + this.maxHeap.front().element) / 2; |
30 | 18 | }
|
31 | 19 |
|
32 |
| - this.array.splice(left, 0, num); |
| 20 | + return this.maxHeap.front().element; |
33 | 21 | }
|
34 | 22 |
|
35 |
| - findMedian(): number { |
36 |
| - if (this.array.length === 0) { |
37 |
| - return 0; |
| 23 | + rebalance() { |
| 24 | + if (this.minHeap.size() + 1 < this.maxHeap.size()) { |
| 25 | + return this.minHeap.enqueue(this.maxHeap.dequeue().element); |
38 | 26 | }
|
39 | 27 |
|
40 |
| - const mid = Math.floor(this.array.length / 2); |
| 28 | + if (this.maxHeap.size() < this.minHeap.size()) { |
| 29 | + return this.maxHeap.enqueue(this.minHeap.dequeue().element); |
| 30 | + } |
| 31 | + } |
41 | 32 |
|
42 |
| - if (this.array.length % 2 !== 0) { |
43 |
| - return this.array[mid]; |
44 |
| - } else { |
45 |
| - return (this.array[mid] + this.array[mid - 1]) / 2; |
| 33 | + getHeap(num: number) { |
| 34 | + if (this.maxHeap.isEmpty() || num <= this.maxHeap.front().element) { |
| 35 | + return this.maxHeap; |
46 | 36 | }
|
| 37 | + |
| 38 | + return this.minHeap; |
47 | 39 | }
|
48 | 40 | }
|
49 | 41 |
|
|
0 commit comments