【问题标题】:How do you find the mode of an Array in java?你如何在java中找到数组的模式?
【发布时间】:2017-02-05 12:03:05
【问题描述】:

我是 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 中得到了错误的结果。有人知道我做错了什么吗?

谢谢!

【问题讨论】:

  • 他做了功课,但面临一些问题@Shadetheartist
  • @rish 可以理解,但 prabod 能够在一分钟内找到可能的重复项,因此这表明 OP 在发布问题之前没有花足够的精力研究他的问题。
  • 我确实看到了那个问题,但发现它使用了哈希图,因为我不知道那是什么,所以我决定发布我自己的问题。 @Shadetheartist
  • 他的问题非常具体。他想知道为什么他在最后 2 次测试中得到错误的结果。而已。不要认为他需要整个代码!

标签: java arrays


【解决方案1】:

您永远不会将除 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 来计算相等的数组条目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-20
    • 2012-08-15
    • 2020-02-27
    • 2013-07-12
    • 2019-05-05
    • 2012-11-25
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多