gpt4 book ai didi

c - 找到数组中出现次数最多的数字

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:26 25 4
gpt4 key购买 nike

我最近开始学习 C,遇到了这个小测试。

Make a code which reads 10 numbers from a user.

Print the Largest & Smallest entered values then print the most frequent number.

让一切对我来说都很简单,但最频繁的数字让我发疯,我搜索了一段时间,找不到任何明确的答案。

我写的代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
int hi[10], i=0, largest, smallest;
while(i<10)
{
printf("Enter a number:");
scanf("%d", &hi[i]);
i++;
}
smallest = hi[0];
largest = hi[0];
printf("Entered Numbers: ");
while(i!=0)
{
if(hi[10-i] < smallest) { smallest = hi[10-i]; }
if(hi[10-i] > largest) { largest = hi[10-i]; }
printf("%d | ", hi[10-i]);
i--;
}

printf("\nLargest number is = %d || Smallest number is = %d", largest, smallest);
return 0;
}

我唯一想到的是:

  • 制作另一个数组。

  • 获取原数组中[i]的值。

  • 将 [i] 与原始数组的其余值进行比较(如果它们相等或不相等)。

  • 如果它们相等,则增加另一个数组的值。

  • 检查另一个数组中的最大值,它应该是出现次数最多的数。

  • 现在,我知道最频繁出现的元素的顺序以及该元素被输入的次数。

最佳答案

使用 HashMap 会更有效率。在那里你可以使用输入的数字作为键并将值设置为 1。当用户给出一个新数字时,你只需要检查新数字是否已经在 map 中。如果是,则将值设置为 2,否则添加值为 1 的新数字。

关于c - 找到数组中出现次数最多的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42491653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com