数据流的中位数
描述
-
中位数是有序整数列表中的中间值。如果列表的大小是偶数,则没有中间值,中位数是两个中间值的平均值。
- 例如 arr = [2,3,4] 的中位数是 3
- 例如 arr = [2,3] 的中位数是 (2 + 3) / 2 = 2.5
-
实现 MedianFinder 类:
MedianFinder()初始化 MedianFinder 对象void addNum(int num)将数据流中的整数 num 添加到数据结构中double findMedian()返回到目前为止所有元素的中位数- 与实际答案相差 1 0 − 5 10^{-5} 10−5 以内的答案将被接受
示例 1
输入
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
输出
[null, null, null, 1.5, null, 2.0]
解释
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // 返回 1.5 ((1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
提示
- - 1 0 5 10^5 105 <= num <= 1 0 5 10^5 105
- 在调用 findMedian 之前,数据结构中至少有一个元素
最多 5 * 1 0 4 10^4 104 次调用 addNum 和 findMedian
Typescript 版算法实现
1 ) 方案1:优先队列
class Heap<T> {
private heap: T[] = [];
private compareFn: (a: T, b: T) => boolean;
constructor(compareFn: (a: T, b: T) => boolean) {
this.compareFn = compareFn;
}
swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
getParentIndex(i: number): number {
return Math.floor((i - 1) / 2);
}
getLeftChildIndex(pi: number): number {
return 2 * pi + 1;
}
getRightChildIndex(pi: number): number {
return 2 * pi + 2;
}
peek(): T | undefined {
return this.heap[0];
}
size(): number {
return this.heap.length;
}
insert(value: T): void {
this.heap.push(value);
this.shiftUp(this.size() - 1);
}
pop(): T | undefined {
const { heap } = this;
if (this.size() === 1) return heap.pop();
const first = heap[0];
heap[0] = heap.pop()!;
this.shiftDown(0);
return first;
}
shiftUp(i: number): void {
if (i <= 0) return;
const { heap } = this;
const pi = this.getParentIndex(i);
if (this.compareFn(heap[pi]!, heap[i]!)) {
this.swap(pi, i);
this.shiftUp(pi);
}
}
shiftDown(pi: number): void {
const { heap } = this;
const size = this.size();
const li = this.getLeftChildIndex(pi);
const ri = this.getRightChildIndex(pi);
if (li < size && this.compareFn(heap[pi]!, heap[li]!)) {
this.swap(pi, li);
this.shiftDown(li);
}
if (ri < size && this.compareFn(heap[pi]!, heap[ri]!)) {
this.swap(pi, ri);
this.shiftDown(ri);
}
}
}
class MinHeap extends Heap<number> {
constructor() {
super((a, b) => a > b);
}
}
class MaxHeap extends Heap<number> {
constructor() {
super((a, b) => a < b);
}
}
// 使用示例
class MedianFinder {
private maxHeap: MaxHeap;
private minHeap: MinHeap;
constructor() {
this.maxHeap = new MaxHeap();
this.minHeap = new MinHeap();
}
addNum(num: number): void {
if (this.maxHeap.size() === 0 || num <= this.maxHeap.peek()!) {
this.maxHeap.insert(num);
} else {
this.minHeap.insert(num);
}
// 平衡两个堆
if (this.maxHeap.size() > this.minHeap.size() + 1) {
this.minHeap.insert(this.maxHeap.pop()!);
}
if (this.minHeap.size() > this.maxHeap.size()) {
this.maxHeap.insert(this.minHeap.pop()!);
}
}
findMedian(): number {
if (this.maxHeap.size() === this.minHeap.size()) {
return (this.maxHeap.peek()! + this.minHeap.peek()!) / 2;
}
return this.maxHeap.peek()!;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/
- 超出时间限制
2 ) 方案2:优先队列-优化版
class Heap {
protected heap: number[] = [];
private compareFn: (a: number, b: number) => boolean;
constructor(compareFn: (a: number, b: number) => boolean) {
this.compareFn = compareFn;
}
protected swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
protected getParentIndex(i: number): number {
return (i - 1) >> 1;
}
protected getLeftIndex(pi: number): number {
return (pi << 1) + 1;
}
protected getRightIndex(pi: number): number {
return (pi << 1) + 2;
}
public peak(): number | undefined {
return this.heap[0];
}
public size(): number {
return this.heap.length;
}
public isEmpty(): boolean {
return this.size() === 0;
}
public insert(value: number): void {
this.heap.push(value);
this.shiftUp(this.size() - 1);
}
public pop(): number | undefined {
if (this.size() === 0) return undefined;
if (this.size() === 1) return this.heap.pop();
const first = this.heap[0];
this.heap[0] = this.heap.pop()!;
this.shiftDown(0);
return first;
}
protected shiftUp(i: number): void {
while (i > 0 && this.compareFn(this.heap[this.getParentIndex(i)], this.heap[i])) {
this.swap(this.getParentIndex(i), i);
i = this.getParentIndex(i);
}
}
protected shiftDown(pi: number): void {
let largest = pi;
const left = this.getLeftIndex(pi);
const right = this.getRightIndex(pi);
if (left < this.size() && this.compareFn(this.heap[largest], this.heap[left])) {
largest = left;
}
if (right < this.size() && this.compareFn(this.heap[largest], this.heap[right])) {
largest = right;
}
if (largest !== pi) {
this.swap(pi, largest);
this.shiftDown(largest);
}
}
}
class MinHeap extends Heap {
constructor() {
super((a, b) => a > b); // Min-heap comparison function
}
}
class MaxHeap extends Heap {
constructor() {
super((a, b) => a < b); // Max-heap comparison function
}
}
class MedianFinder {
private maxHeap: MaxHeap;
private minHeap: MinHeap;
constructor() {
this.maxHeap = new MaxHeap(); // Max-heap for the smaller half of numbers
this.minHeap = new MinHeap(); // Min-heap for the larger half of numbers
}
public addNum(num: number): void {
if (this.maxHeap.isEmpty() || num <= this.maxHeap.peak()!) {
this.maxHeap.insert(num);
} else {
this.minHeap.insert(num);
}
// Balance the heaps
if (this.maxHeap.size() > this.minHeap.size() + 1) {
this.minHeap.insert(this.maxHeap.pop()!);
} else if (this.minHeap.size() > this.maxHeap.size()) {
this.maxHeap.insert(this.minHeap.pop()!);
}
}
public findMedian(): number {
if (this.maxHeap.size() === this.minHeap.size()) {
return (this.maxHeap.peak()! + this.minHeap.peak()!) / 2;
}
return this.maxHeap.peak()!;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/
3 ) 方案3:有序集合 + 双指针
class MedianFinder {
private nums: Map<number, number> = new Map();
private orderedKeys: number[] = [];
private n: number = 0;
private left: [number, number] = [0, 0];
private right: [number, number] = [0, 0];
constructor() {}
public addNum(num: number): void {
// Update the frequency of the number in the map
const count = this.nums.get(num) || 0;
this.nums.set(num, count + 1);
// Maintain the ordered keys list
if (!this.orderedKeys.includes(num)) {
const index = this.bisectLeft(this.orderedKeys, num);
this.orderedKeys.splice(index, 0, num);
}
if (this.n === 0) {
this.left = [num, 1];
this.right = [num, 1];
} else if ((this.n & 1) !== 0) {
if (num < this.left[0]) {
this.decrease('left');
} else {
this.increase('right');
}
} else {
if (num > this.left[0] && num < this.right[0]) {
this.increase('left');
this.decrease('right');
} else if (num >= this.right[0]) {
this.increase('left');
} else {
this.decrease('right');
this.left = [...this.right];
}
}
this.n++;
}
public findMedian(): number {
return (this.left[0] + this.right[0]) / 2;
}
private increase(iterator: 'left' | 'right'): void {
const it = iterator === 'left' ? this.left : this.right;
it[1]++;
if (it[1] > (this.nums.get(it[0]) || 0)) {
const nextKeyIndex = this.bisectLeft(this.orderedKeys, it[0] + 1);
it[0] = nextKeyIndex < this.orderedKeys.length ? this.orderedKeys[nextKeyIndex] : this.orderedKeys[this.orderedKeys.length - 1];
it[1] = 1;
}
}
private decrease(iterator: 'left' | 'right'): void {
const it = iterator === 'left' ? this.left : this.right;
it[1]--;
if (it[1] <= 0) {
const prevKeyIndex = this.bisectRight(this.orderedKeys, it[0] - 1) - 1;
it[0] = prevKeyIndex >= 0 ? this.orderedKeys[prevKeyIndex] : this.orderedKeys[0];
it[1] = this.nums.get(it[0]) || 0;
}
}
private bisectLeft(arr: number[], x: number): number {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (arr[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
private bisectRight(arr: number[], x: number): number {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (x < arr[mid]) hi = mid;
else lo = mid + 1;
}
return lo;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/
- 超出时间限制
9947



被折叠的 条评论
为什么被折叠?



