Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java O(n)中数组的查找模式_Java_Algorithm_List_Collections_Time Complexity - Fatal编程技术网

Java O(n)中数组的查找模式

Java O(n)中数组的查找模式,java,algorithm,list,collections,time-complexity,Java,Algorithm,List,Collections,Time Complexity,我想我做对了,找到O(n)中的模式。但当计时时,它似乎更接近O(n*log(n)): public int模式(列表numList){ //保持频率 int[]频率=新的int[Collections.max(numList)+1]; 对于(inti=0;i您几乎是对的,因为大多数操作都需要O(n)时间,流除外。它们可能需要比O(n)更多的时间即使在遍历长度为n的Iterable。更多。类似于指定的@Andronicus,您也可以摆脱流,使用纯数组而不是偶列表。但同样,使用这种方法,您的时间复杂

我想我做对了,找到O(n)中的模式。但当计时时,它似乎更接近O(n*log(n)):

public int模式(列表numList){
//保持频率
int[]频率=新的int[Collections.max(numList)+1];

对于(inti=0;i您几乎是对的,因为大多数操作都需要O(n)时间,流除外。它们可能需要比O(n)更多的时间即使在遍历长度为n的
Iterable
。更多。

类似于指定的@Andronicus,您也可以摆脱流,使用纯数组而不是偶列表。但同样,使用这种方法,您的时间复杂度不是
O(n)
,而是
O(m)
,其中
m
是数组中的最大元素。也如注释中所述,您的方法不适用于负值。在这种情况下,
HashMap
是您的最佳选择,大多数时间保证
O(1)
插入/获取用于计算简单类型(如整数)的哈希值。

您所做的就像是计数排序。它不会为每个输入生成输出。
[12147483647]
[-4,-5,-6]
您为分布不均匀的列表分配了太多内存。最好使用哈希映射在O(n)中进行计算时间。@vivek_23他正在寻求家庭作业方面的帮助。他早些时候发布了这个问题,结果被否决了。然后他删除了它。他的教授特别要求O(n*log(n))。我早些时候告诉他怎么做O(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;
}