寻找未排序数组的众数,如果该数组有多个众数或没有众数

3
我正在尝试找到一种方法来查找未排序数组的众数,如果该未排序数组本身就有众数,或者它有多个众数(例如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;

这种方法可以完成任务,但不能帮助我确定数组是否有多个众数。当没有众数时,它只输出数组中的第一个值。

对此有何帮助吗?提前感谢您。


使用 std::adjacent_find 函数。 - user1593881
1个回答

2

你可以在不改变算法的前提下,先进行第一轮迭代以获取众数计数,然后再进行另一轮迭代以获取所有重复该次数的元素。

另一种算法是保存每个数字及其出现次数的直方图。这可以通过c++的map实现,它保存数据的键值对。在填充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 -> %d\n", element.first, element.second);
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接