【发布时间】:2019-03-19 18:05:40
【问题描述】:
我认为我做对了,在 O(n) 中找到模式。但是在计时时,它似乎需要更接近 O(n*log(n)):
public int mode(List<Integer> numList) {
//Holds frequencies
int[] frequencies = new int[Collections.max(numList)+1];
for(int i=0; i<numList.size(); i++) {
frequencies[numList.get(i)]+=1;
}
//Convert to List
List<Integer> freqArray = IntStream.of(frequencies).boxed().collect(Collectors.toCollection(ArrayList::new));
int maxFreq = Collections.max(freqArray);
int mode = freqArray.indexOf(maxFreq);
return mode;
}
我哪里错了?谢谢
【问题讨论】:
-
你所做的就像计数排序一样。它不会为每个输入产生输出。
[1,2147483647]或[-4,-5,-6] -
您为不均匀分布的列表分配了太多内存。最好使用 HashMap 在 O(n) 时间内计算。
-
@vivek_23 他正在寻求家庭作业方面的帮助。他早些时候发布了这个问题,但它被否决了。然后他删了。他的教授特别要求 O(n*log(n))。我之前告诉他怎么做 O(n)。
标签: java algorithm list collections time-complexity