我正在寻找一种优雅的方法来确定 C++ ptr 数组中哪个元素出现次数最多(模式)。
例如,在
{"pear", "apple", "orange", "apple"}
该"apple"
元素是最常见的元素。
我以前的尝试失败了编辑:数组已经排序。
int getMode(int *students,int size)
{
int mode;
int count=0,
maxCount=0,
preVal;
preVal=students[0]; //preVall holds current mode number being compared
count=1;
for(int i =0; i<size; i++) //Check each number in the array
{
if(students[i]==preVal) //checks if current mode is seen again
{
count++; //The amount of times current mode number has been seen.
if(maxCount<count) //if the amount of times mode has been seen is more than maxcount
{
maxCount=count; //the larger it mode that has been seen is now the maxCount
mode=students[i]; //The current array item will become the mode
}else{
preVal = students[i];
count = 1;
}
}
}
return mode;
}