查找未排序数组的模式,以及该数组是否具有多个模式或无模式

Find the mode of an unsorted array and if that array has more than one mode or no mode

本文关键字:模式 数组 是否 排序 查找      更新时间:2023-10-16

我试图弄清楚如何找到未排序数组的模式,如果该未排序数组具有开始的模式,或者如果它具有多个模式(即 2,2,3,3,4,6,7,其中模式为 2 和 3(。

我正在尝试弄清楚如何在不事先对数组进行排序的情况下执行此操作。

目前,我有这个:

int counter = 1;
int counterTwo = 0;
int mode = array[0];
for (int i = 0; i < SIZE - 1; i++)
{
    if (array[i] == array[i + 1])
    {
        counter++;
        if (counter > counterTwo)
        {
            counterTwo = counter;
            mode = array[i];                
        }
        else
        {
            counter = 1; // Reset counter
        }
    }
}
cout << "nThe mode is: " << mode << endl;

哪种可以完成工作,但不能帮助我确定阵列是否具有多个模式。当没有模式时,它只输出数组中的第一个值。

对此有任何帮助吗?提前谢谢你。

在不更改算法的情况下,您可以做的一件事是执行第一次迭代以获取模式计数,然后执行另一次迭代以获取重复该次数的所有元素。

您可以使用的另一种算法是保存每个数字及其出现次数的直方图。这可以通过c++map来实现,它保存了数据的键值对。在提交map时,您还可以保存模式计数,然后遍历映射以获取具有该计数的元素。

示例代码

int count = 7;
int array[] = {2, 2, 3, 3, 4, 6, 7};
std::map<int, int> histogram;
int mode_count = 0;
for (int i = 0; i < count; i++) {
  int element = array[i];
  histogram[element]++;
  mode_count = std::max(mode_count, histogram[element]);
}
for (auto element : histogram) {
  if (element.second == mode_count) {
    printf("%d -> %dn", element.first, element.second);
  }
}