我已经想出了如何创建一个整数数组并创建一个方法来查找数组中最常见的值。通过创建另一个用作每个值的计数器的数组来创建此方法。但是我怎样才能创建一个用于在DOUBLES数组中找到最常用双精度的方法而不使用散列图或排序?
- 这是我使用整数的方法的代码,但不适用于double值/ double数组
public static int findMostFrequentValue(int[] array) {
int i;
int[] numberCount = new int[100];
for (i = 0; i < array.length; i++)
++numberCount[array[i]];
int max = 0;
int j;
for (j = 0; j < numberCount.length; j++) {
if (numberCount[j] > max) max = j;
}
return max;
}
答案 0 :(得分:1)
这里有一个快速的模糊,坚持你没有哈希图或排序的要求。注意,作为编码,如果有平局则返回最后一个匹配。另请注意,内部循环是指数 O(n ^ 2)时间,因此对于大型数组来说很差。
public class Frequency {
public static void main(String args[]) {
double[] array = {3.4, 6.8, 1.1, 2.4, 3.8, 6.8, 7.0, 5.0};
double result = findMostFrequentValue(array);
System.out.println("Most frequent value: " + result);
}
public static double findMostFrequentValue(double[] array) {
int[] count = new int[array.length];
for (int i = 0; i < array.length; i++) {
count[i] = 0;
for (int j = 0; j < array.length; j++) {
if (approxEquals(array[i], array[j], .0001)) {
count[i]++;
}
}
}
int index = 0;
int max = 0;
for (int i = 0; i < count.length; i++) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
return array[index];
}
private static boolean approxEquals(double val1, double val2, double tolerance) {
return Math.abs(val1 - val2) < tolerance;
}
}