如何计算 java 中排序数组的众数

how to calculate mode for a sorted array in java

所以我正在编写一种方法来计算排序数组的模式。但是当我打印出模式值时,它总是显示为 0.00,我试图修复它但不能。 这是我对此方法的代码: (numRead为传入的数组,num为实际有值的数组长度)

public static void modeCalc(double[] numRead, int num)
    {
        double maxValue = numRead[0];
        int maxCount = 0;
        for (int i = 0; i < numRead.length; i++)
        {
            int count = 0;
            for (int j = 0; j < numRead.length; j++)
            {
                if (numRead[j] == numRead[i])
                    count++;
            }
            if (count > maxCount)
            {
                maxCount = count;
                maxValue = numRead[i];
            }
        }
        return maxValue;
    }

非常感谢任何帮助!

粗略一瞥表明您的数组在排序数据的末尾有更多的 0 值,这些成为众数。这似乎是问题所在,它指出 numRead 是排序的数组,但它只有 num 值有意义。循环搜索数组到末尾,而不是搜索具有良好值的元素的数量。将 numRead.length 更改为 num 并查看是否有帮助。另外,尝试传递一个完整的数组(没有空元素),看看它是否工作得更好。很可能空元素被初始化为零,并且空元素的数量比任何其他值都多。

这应该有效。你需要 return 一个 double,你需要使用 num.

class ModeArray
{
    public static void main(String[] args) {
        double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
        System.out.println(modeCalc(numRead, 8));
    }

    public static double modeCalc(double[] numRead, int num) {
        double maxValue = numRead[0];
        int maxCount = 0;
        for (int i = 0; i < num; i++) {
            int count = 0;
            for (int j = 0; j < num; j++) {
                if (numRead[j] == numRead[i]){
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = numRead[i];
            }
        }
        return maxValue;
    }
}

如果您知道数组已排序,则应使用此信息。

public static double modeCalc(double[] numRead, int num) {
    double maxValue = numRead[0];
    double lastValue = maxValue;
    int count = 1;
    int maxCount = 1;
    for (int i = 1; i < num; i++) {
        if (numRead[i] == lastValue) {
            count++;
        } else {
            count = 1;
            lastValue = numRead[i];
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = lastValue;
        }
    }
    return maxValue;
}

PS: 请不要使用没有大括号的 if 语句。它使添加错误更容易,但更难找到它们。