我需要编写一个函数来查找数组的模式。然而,我不擅长提出算法,我希望其他人知道如何做到这一点。
我知道数组的大小和每个元素中的值,并且我将数组从最小到最大排序。
数组将被传递给模式函数,例如
模式 = findMode(arrayPointer, sizePointer);
UPDATE:
阅读评论后我尝试过这个
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;
}
尽管有人可以解决我的问题,但我在掌握这个算法时仍然遇到问题。
我从未使用过向量,所以不太理解其他示例。
你几乎拥有一切。
您可以利用数组已排序的事实。
只需遍历数组来跟踪两个current相等的连续数,并且greatest直到该点为止您找到的相等连续数字的数量(以及哪个数字产生了它)。最后你将得到最大数量的相等的连续数字以及哪个数字产生了它。这就是模式。
Note:对于一个解决方案not要求数组已排序,请参见示例一种基于直方图的方法 in a 相关问题.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)