c++ - 如何找到排序数组的模式?

标签 c++ arrays algorithm sorting

我需要编写一个函数来查找数组的模式。然而,我不擅长提出算法,我希望其他人知道如何做到这一点。

我知道数组的大小和每个元素中的值,并且我将数组从小到大排序。

数组将像这样传递给模式函数

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 approachrelated question .

关于c++ - 如何找到排序数组的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316352/

相关文章:

c++ - C++中的共享字符串常量

c++ - 将对象指针的数据成员数组初始化为正确的大小和 null

arrays - 使用数组参数创建 bash 选择菜单

php - 类型检查所有数组元素

arrays - 查找数组中符合条件的中间值

java - 基于文本搜索的算法未按预期运行

c++ - 图像处理库

c++ - 将 std::string 转换为 boost::asio::streambuf

algorithm - 最大化给定约束的多个变量的总和

algorithm - 什么是 O(n*log m) + O(m)?