查找未排序数组的模式,以及该数组是否具有多个模式或无模式
Find the mode of an unsorted array and if that array has more than one mode or no mode
我试图弄清楚如何找到未排序数组的模式,如果该未排序数组具有开始的模式,或者如果它具有多个模式(即 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);
}
}
相关文章:
- C++ 无法在字符数组中使用 for 循环打印字母模式
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在数组中查找重复模式
- 如何在 2D 数组中编写此模式?
- 在数组中查找模式的最有效方法?
- 如何以模式获取数组中的数据?
- 从列表到数组C 查找模式或最常见的数字
- 查找未排序数组的模式,以及该数组是否具有多个模式或无模式
- 如何通过将数组的指针传递给函数来查找数组的模式?C++
- 在数组中查找一个或多个模式
- 为什么使用char数组来存储以二进制模式打开的文件的内容
- 正在初始化带模式的“constexpr”数组
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- 无模式例外是什么意思?(数组中出现次数最多的数字)
- 在调试模式下释放静态数组时出错
- 在多线程代码中缓存友好的数组迭代模式
- 如何以特定模式对字符串数组进行排序
- 在函数搜索模式中引用二维数组时出错
- 如何在字节数组中搜索模式
- 数组类型具有用于模式匹配的不完整元素类型