【发布时间】:2017-03-28 14:45:04
【问题描述】:
这是一个常见的面试问题。 你有一个数字流进来(假设超过一百万)。数字在 [0-999] 之间)。
Implement a class which supports three methods in O(1)
* insert(int i);
* getMean();
* getMedian();
这是我的代码。
public class FindAverage {
private int[] store;
private long size;
private long total;
private int highestIndex;
private int lowestIndex;
public FindAverage() {
store = new int[1000];
size = 0;
total = 0;
highestIndex = Integer.MIN_VALUE;
lowestIndex = Integer.MAX_VALUE;
}
public void insert(int item) throws OutOfRangeException {
if(item < 0 || item > 999){
throw new OutOfRangeException();
}
store[item] ++;
size ++;
total += item;
highestIndex = Integer.max(highestIndex, item);
lowestIndex = Integer.min(lowestIndex, item);
}
public float getMean(){
return (float)total/size;
}
public float getMedian(){
}
}
我似乎想不出在 O(1) 时间内获得中位数的方法。 任何帮助表示赞赏。
【问题讨论】:
-
为什么不能像使用
total一样更新insert的中位数(保存为(值,值中的数字))? -
鉴于您的
store具有固定 (1000) 个元素,几乎您编写的任何用于计算中位数的代码都是 O(1)。 -
@PaulHankin 它没有固定数量的元素。您可能想再次阅读该问题。
-
@Abstraction 这就是我想要做的,但似乎找不到办法。
-
@MelissaStewart Paul 是对的,
store具有固定数量的元素 (1000)。插入多少值无关紧要。见my answer。
标签: java algorithm data-structures