程序获取数组的大小和数组元素作为输入。并且程序应该打印此数组中重复次数最少的最小元素。
数组的大小是从1到100。
数字范围从1到100。
例如,如果输入是[1,2,1,3,4],则输出必须是2。
我试图找出每个数组元素的重复次数,然后以某种方式将它与原始问题联系起来,但我找不到方法。
非常感谢您抽出宝贵时间并提前提供帮助。
最佳答案
int main ()
{
// array input
int ar[] = { 1, 1, 2, 2, 2, 3, 3, 3, 3, 5, 6, 6, 6 };
size_t n = sizeof (ar) / sizeof (ar[0]);
// since maximun size of the array element is 100
int occurrence[101];
// set occurrence to zero
memset (occurrence, 0, sizeof occurrence);
for (int i = 0; i < n; i++)
{
// count the occurrence of each number
occurrence[ar[i]]++;
}
// let's set minValue to INT_MAX
int minValue = INT_MAX, Value;
// since the number range is 1 to 100
for (int i = 1; i <= 100; i++)
{
// Update minValue and Value
if (occurrence[i] != 0 and occurrence[i] < minValue)
{
minValue = occurrence[i];
Value = i;
}
}
// print the result
printf ("%d", Value);
return 0;
}
输出:
5
关于c++ - 找到具有最少重复次数的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899646/