这是一个常见的面试问题。您会接收到一串数字(假设超过一百万个),这些数字介于[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)时间内获取中位数的方法。任何帮助都将不胜感激。
store
有固定数量的元素(1000个)。无论插入多少值都没有关系。请参见我的答案。 - Andreasstore = new int[1000];
保证了store
具有固定数量的元素。你可能需要重新阅读你的代码。 - Lew Bloch