对于这个问题,我将编写一个名为 mode 的方法,该方法返回整数数组中出现频率最高的元素。假设数组至少有一个元素,并且数组中的每个元素都有一个介于 0 和 100 之间的值。通过选择较低的值打破联系。
例如,如果传递的数组包含值 {27, 15, 15, 11, 27},则您的方法应返回 15。(提示:您可能希望查看本章前面的 Tally 程序以了解如何解决这个问题呢。)
我在查看特定输入出了什么问题时遇到了问题。例如:
mode({27, 15, 15, 27, 11, 11, 11, 14, 15, 15, 16, 19, 99, 100, 0, 27}) 返回 15,这是正确的,但是 mode({1, 1, 2, 3, 3}) 当它应该是 1 时返回 3。
这是代码:
public static int mode(int[] input) {
int returnVal = input[0]; // stores element to be returned
int repeatCount = 0; // counts the record number of repeats
int prevRepCnt = 0; // temporary count for repeats
for (int i=0; i<input.length; i++) { // goes through each elem
for (int j=i; j<input.length; j++) { // compares to each elem after the first elem
if (i != j && input[i] == input[j]) { // if matching values
repeatCount++; // gets the repeat count
if (repeatCount>=prevRepCnt) { // a higher count of repeats than before
returnVal=input[i]; // return that element
}
prevRepCnt = repeatCount; // Keeps the highest repeat record
}
repeatCount=0; // resets repeat Count for next comparison
}
}
return returnVal;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这里有一个更简单的方法来解决这个问题。创建一个大小为 101 的名为 count 的数组。索引 (0-100) 表示您正在计算的数字。遍历输入数组并计算每个数字的出现次数。最后,比较计数以找到出现最多的计数(并列到较低的数字):
public static int mode(int[] input) {
int[] count = new int[101];
//count the occurrences
for (int i=0; i < input.length; i++) {
count[input[i]]++;
}
//go backwards and find the count with the most occurrences
int index = count.length-1;
for (int i=count.length-2; i >=0; i--) {
if (count[i] >= count[index])
index = i;
}
return index;
}
Run Code Online (Sandbox Code Playgroud)
我最近分析了四种计算数组众数的方法:
您可以在本文中找到所有四种方法的源代码(尽管是 C# 的)和性能比较:Finding Mode of an Array