假设我有一系列双打,如下所示:
Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}
Run Code Online (Sandbox Code Playgroud)
我需要一个函数来确定数组中MAJORTY投票的内容,在本例中为"10",因为它是最常出现的数字......当然还有没有多数投票的情况(它们在哪里)等于),在这种情况下,我需要抛出异常......
有线索吗?除了在数组上做一些非常讨厌的循环之外(对于每个索引,确定存在多少具有相同值的数量,在数组中存储计数,然后扫描计数数组中的最高数字,并且该位置的值是赢家等...)
我需要做作业才能获得阵列中最"流行"的数字(最高频率的数字),如果有多个数字具有相同数量的节目,请随机获取一些数字.经过三个多小时的尝试,并在网上搜索,这就是我得到的:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return …Run Code Online (Sandbox Code Playgroud)