我必须编写一个程序来查找数组中的重复项以及每个重复项在数组中出现的次数。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define DIM 5
int contains (int v[], int dim, int n);
int main(int argc, char** argv)
{
int i, j, k = 0, found;
int v[DIM];
int dup[DIM] = {0};
for (i = 0; i < DIM; i++)
{
printf("Insert element in the array: ");
scanf("%d", &v[i]);
}
for (i = 0; i < DIM; i++)
{
found = 0;
if (contains (dup, DIM, v[i]) == 0)
{
for (j = 0; j < DIM; j++)
{
if (v[i] == v[j] && (i != j))
{
found ++;
dup[k] = v[i];
k++;
}
}
if (found != 0)
{
printf("Element %d has been repeated %d times\n", v[i], found);
}
}
}
return (0);
}
int contains (int v[], int dim, int n)
{
int i;
int found = 0;
for (i = 0; i < dim; i++)
{
if (v[i] == n)
{
found = 1;
}
}
return found;
}
该程序运行良好,但我认为它不是很有效。当然,它存在一种让程序高效的方法,不是吗?我的意思是一种继续使用数组而不是任何其他结构的方法