如下:
#include
#include
int main()
{
int n;
int *a;
int i;
scanf("%d", &n);
a = (int *)malloc(sizeof(int) * n);
for(i = 0; i < n; i ++)
{
scanf("%d", &a[i]);
}
for(i = 0; i < n - 1; i ++)
{
for(int j = 0; j < n - i - 1; j ++)
{
if(a[j] > a[j+1])
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
int tmp = a[0];
int count = 1;
for(i = 1; i < n; i ++)
{
if(tmp == a[i])
{
count ++;
}
else
{
if(count > 1)
{
printf("数组共有%d个数字%d\n", count, a[i - 1]);
}
tmp = a[i];
count = 1;
}
}
if(count > 1)
{
printf("数组共有%d个数字%d\n", count, a[i - 1]);
}
free(a);
return 0;
}
我的思路是,先排序,再输出。
代码如下 :
#include
#define MAX 100 // 数组最大数
typedef struct _Node {
int value;
int count;
}Node;
typedef struct {
Node values[MAX];
int size;
}List;
Node *List_Add(List *pList, int value) {
Node *pNode = &pList->values[pList->size];
pNode->value = value;
pNode->count = 1;
pList->size++;
return pNode;
}
Node *List_Find(List *pList, int value)
{
int i;
for (i = 0; i < pList->size; i++) {
if (pList->values[i].value == value) {
return &pList->values[i];
}
}
return NULL;
}
int main()
{
int numbers[MAX], n, i;
List list;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &numbers[i]);
}
list.size = 0;
for (i = 0; i < n; i++) {
Node *pNode = List_Find(&list, numbers[i]);
if (pNode != NULL) {
pNode->count++;
}
else {
List_Add(&list, numbers[i]);
}
}
for (i = 0; i < list.size; i++) {
if (list.values[i].count >= 2) {
printf("数组共有%d个数字%d\n", list.values[i].count, list.values[i].value);
}
}
return 0;
}
运行结果: