【发布时间】:2014-07-19 17:30:33
【问题描述】:
对于这个问题,我将编写一个名为 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;
}
【问题讨论】: