【发布时间】:2018-08-12 21:57:11
【问题描述】:
最近我正在尝试使用 C 在一组数字中找到模式。 我的代码在集合很小的情况下可以做得很好。
这是我的代码:
int frequency[10001]; //This array stores the frequency of a number that between 0 to 10000
int main()
{
int x[10]={1,6,5,99,1,12,50,50,244,50};
int highest = 0;
int i,j,k;
for(i=0;i<10;i++)
{
frequency[x[i]]++;
if(frequency[x[i]]>highest)
highest = frequency[x[i]];
}
printf("The mode in the array : ");
for(i=0;i<=10001;i++)
if(frequency[i]==highest)
printf("%d ",i);
return 0;
}
后来,我发现如果有大量的数字,我的方法会非常慢。此外,如果数字小于 0 或大于 10000,我的程序将无法运行,除非我增加“频率”数组的大小。
因此,我想知道有什么方法可以更有效地找到数组中的模式?谢谢。
【问题讨论】:
-
小心:
for(i=0;i<=10001;i++)=>for(i=0;i<10001;i++) -
我会给你一个提示,获取数组中的最大数,然后像这样定义数组频率[max_number]
-
为什么不存储
highest时也存储index的highest所在的位置,这样可以节省第二遍。将此与上面给出的提示相结合以找到最大值。也可以将 unordered_map 与save the highest策略一起使用。 -
C 还是 C++?选择一个。
-
点击以下链接获取答案:stackoverflow.com/questions/19920542/…