对于这个问题,我要编写一个名为mode的方法,它返回一个整数数组中最常出现的元素.假设数组至少有一个元素,并且数组中的每个元素都具有0到100之间的值(包括0和100).通过选择较低的值来打破关系.
例如,如果传递的数组包含值{27,15,11,27},则您的方法应返回15.(提示:您可能希望查看本章前面的Tally程序以了解如何解决这个问题呢.)
我在查看特定输入的错误时遇到问题.例如:
模式({27,27,14,16,19,99,100,27})返回15这是正确的,但模式({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; }
解决方法
这是解决此问题的更简单方法.创建一个名为count的大小为101的数组.索引(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; }