【问题标题】:Find the mode of an unsorted array and if that array has more than one mode or no mode查找未排序数组的模式以及该数组是否具有多个模式或没有模式
【发布时间】:2017-02-12 23:27:11
【问题描述】:

我试图弄清楚我将如何找到未排序数组的模式,如果该未排序数组有一个模式开始,或者它有多个模式(即 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++ arrays nested-loops


【解决方案1】:

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

您可以使用的另一种算法是保存每个数字及其出现次数的直方图。这可以通过 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 -> %d\n", element.first, element.second);
  }
}

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2011-11-27
    • 2012-03-08
    • 2021-10-11
    相关资源
    最近更新 更多