我需要编写一个函数来查找数组的模式。然而,我不擅长提出算法,我希望其他人知道如何做到这一点。
我知道数组的大小和每个元素中的值,并且我将数组从小到大排序。
数组将像这样传递给模式函数
mode = findMode(arrayPointer, sizePointer);
更新:
看完评论我试过了
int findMode(int *arrPTR, const int *sizePTR)
{
int most_found_element = arrPTR[0];
int most_found_element_count = 0;
int current_element = arrPTR[0];
int current_element_count = 0;
int count;
for (count = 0; count < *sizePTR; count++)
{
if(count == arrPTR[count])
current_element_count++;
else if(current_element_count > most_found_element)
{
most_found_element = current_element;
most_found_element_count = current_element_count;
}
current_element = count;
current_element_count=1;
}
return most_found_element;
}
如果有人能解决我的问题,我仍然无法掌握该算法。 我从未使用过 vector ,所以不太了解其他示例。
最佳答案
你几乎拥有一切。
您可以利用数组已排序这一事实。
只需遍历数组,同时跟踪当前 相等的连续数字,以及您在该点之前找到的最大 相等连续数字的数量(以及哪个数字制作出来的)。最后,您将拥有最大数量的相等连续数字以及产生它的数字。这将是模式。
注意:对于不需要对数组进行排序的解决方案,请参见示例 one based in the histogram approach在related question .
关于c++ - 如何找到排序数组的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316352/