二维数组中数字的最大显示数

max shows of number in two dimension array

本文关键字:显示 数字 二维数组      更新时间:2023-10-16

>我有一个二维数组,我知道:

  • 数和每行的长度
  • 每行只包含正数
  • 每行都按顺序排序
  • 不与辅助阵列一起使用 -不与数据结构一起使用

所需输出

我需要以有效的方式返回在整个数组中出现次数最多的数字。 我已经尝试遍历整个数组,但它效率不高。

这是数组的一个示例。

{
{5, 7, 8},
{6, 6},
{null},
{5, 6, 8, 9}
}

此示例的预期返回值为 6。

我想获得 c++ 中的解释或代码

谢谢

由于需要 C/C++ 解决方案,因此可以使用 2D 阵列。 所有缺失值都可以用 -1 表示(或搜索中涉及的有效数字中不需要的任何数字)。 因此,空行可以用所有 -1 表示。请参阅下面的代码。 由于在 C/C++ 中,2D 数组在内存中连续表示。因此,我们可以将 2D 数组转换为 1D 数组。 现在我们可以对数组进行排序。排序后,所有"-1"都将位于开头,可以丢弃。 从剩余的元素中,我们可以找到元素的最大频率。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int i, prev, max = -1, count = 0, maxvalue = -1;
int a[4][4] = {{5, 7, 8, -1}, {6, 6, -1, -1}, {-1, -1, -1, -1}, {5, 6, 8, 9}};
//int a[4][4] = {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}};
int *b = (int*)a;
int total = sizeof(a) / sizeof(int);
qsort(b, total, sizeof(int), compare);
for(i = 0; i < total; ++i)
{
if(b[i] != -1)
{
break;
}
}
//printf("n");
i = i + 1;
prev = -1;
count = 0;
if(i < total)
{
prev = b[i];
count = 1;
}
for(i = i + 1; i < total; ++i)
{
//printf("prev=%d, b[i]=%d, max=%d, count=%dn", prev, b[i], max, count);
if(prev == b[i])
{
count++;;
}
else
{
if(max < count)
{
max = count;
maxvalue = prev;
}
prev = b[i];
count = 1;
}
}
if(max != -1)
{
printf("Max Occurence of %d = %dn", maxvalue, max);
}
else
{
printf("All the rows are of zero lengthn");
}
return 0;
}
//Output:
Max Occurence of 6 = 3

为了计算元素在数组中出现的次数,这里显示了使用递归的类似问题。

由于您提到了效率,因此在计算数组中元素存在的次数(如果未排序)之前,按增加或减少的顺序对数组进行排序会有所帮助。尽管对于示例中所示的小输入大小,它不会产生太大区别。

您可以使用 map 来跟踪其重复次数和当前最大值。

map<int, int> temp;
int currentMax= -999999,maxCount=0;
for(i=0; i< numberOflines ;i++)
{
for(j=0;j< array[i].length;j++)
{
int newCount = ++temp[array[i][j]];
if (maxCount < newCount) {
maxCount = newCount;
currentMax = array[i][j];
}
}
}

首先,您的输入是非法的:

{
{5, 7, 8},
{6, 6},
{null},
{5, 6, 8, 9}
}

null不是由C++定义的,即使它被定义为 0,也必须被解释为int(0),而不是我认为您想要的空子数组。

我猜你打算暗示的输入应该看起来像这样:

const initializer_list<int> a[] = {{5, 7, 8}, 
{6, 6},
{},
{5, 6, 8, 9}};

您需要为任何数组中的每个数字维护一个总计。最好的方法是使用map<int, int> totals,它只会用确切的pair数构造,因为a中有唯一的元素。每个pair的第二个元素将是到目前为止看到的该元素的计数。您可以通过以下方式填充它:

for(const auto& i : a) for_each(cbegin(i), cend(i), [&](const auto& it){ totals[it]++;});

填充totals后,只需找到其最大值:

cout << max_element(cbegin(totals), cend(totals), [](const auto& lhs, const auto& rhs){return lhs.second < rhs.second;})->first << endl;

现场示例