针对这个问题,我需要编写一个名为mode的方法,该方法返回整数数组中出现次数最多的元素。假设数组至少有一个元素,并且数组中的每个元素的值都在0到100之间(包括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})返回3,而不是1。
以下是代码:
例如,如果传递的数组包含以下值{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})返回3,而不是1。
以下是代码:
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;
}