你如何在java中找到数组的模式?

时间:2016-09-27 18:19:28

标签: java arrays

我是java的新手,我有一个家庭作业,我需要找到平均值,中位数和数组模式。出于某种原因,我的代码没有提出正确的答案。

以下是我为创建数组而提供的代码:

public static void main(String[] args) {

    int[] test01 = new int[]{2,2,2,2,2};
    int[] test01Results = new int[]{2,2,2,2};

    int[] test02 = new int[]{1,2,1,3,5,6,6,1,2,2,2,99,100};
    int[] test02Results = new int[]{2,2,17,100};

    int[] test03 = new int[]{100,200,300,400,300};
    int[] test03Results = new int[]{300,300,260,400};

    int[] test04 = new int[]{100};
    int[] test04Results = new int[]{100,100,100,100};

    int[] test05 = new int[]{100,1};
    int[] test05Results = new int[]{1,100,50,100};

以下是我试图计算模式的原因:

public int mode() {
    int result = 0;
    // Add your code here

    int repeatAmount = 0; //the amount of repeats accumulating for the current i
    int highestRepeat=0; // the highest number of repeats so far
        for (int i=0; i<numberArray.length; i++) { 
            for (int j=i; j<numberArray.length; j++) { 
                if (i != j && numberArray[i] == numberArray[j]) { 
                    repeatAmount++;

                    if (repeatAmount>highestRepeat) { 
                        result=numberArray[i];
                    }
                    repeatAmount = highestRepeat; 
                }
                repeatAmount=0; // resets repeat Count for next comparison
            }
        }
    return result;
}

我得到了测试1,2和3的正确结果,但是测试4和5得到了错误的结果。有谁知道我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

您永远不会将除0以外的任何内容分配给highestRepeat。这应该有效:

public int mode() {
    int result = 0;
    int highestRepeat=0;
    for (int i=0; i<numberArray.length; i++) { 
        int repeatAmount = 1;
        for (int j = i + 1; j < numberArray.length; j++) { 
            if (numberArray[i] == numberArray[j]) { 
                repeatAmount++;
                if (repeatAmount > highestRepeat) { 
                    result = numberArray[i];
                    highestRepeat = repeatAmount;
                }
            }
        }
    }
    return result;
}

其他一些改进:

  • 通过i+1启动内部循环,您可以跳过检查i != j
  • 通过在外部循环中声明repeatAmount,您可以跳过 在内循环后将其设置为零。

如果您需要一些性能,请考虑使用HashMap来计算相等的数组条目。

相关问题