找出数组中重复次数最多的元素并打印
思路:对于这道题应该先进行排序,然后遍历。
代码:
#include<stdio.h>
#include<stdlib.h>
int int_compare(const void *x1, const void *x2)
{
int* a=(int*)x1;
int* b=(int*)x2;
return (*a-*b);
}
void findremax(int a[],int n,int *m,int *c)
{
int index,count,maxc,i;
index=0;
count=1;
maxc=count;
for(i=1;i<n;i++){
if(a[i]==a[i-1])
count++;
else{
if(count>maxc){
maxc=count;
index=i-1;
}
count=1;
}
}
if(count>maxc){
maxc=count;
index=i-1;
}
*m=index;
*c=maxc;
}
int main()
{
int maxindex,c;
int a[]={1,1,2,2,3,3,3,3,4,5,6,7,7,7,7,7,7};
int n=(sizeof(a))/sizeof(a[0]);
maxindex=0;
c=0;
qsort(a,n,sizeof(a[0]),int_compare);
findremax(a,n,&maxindex,&c);
printf("%d appears %d times.\n",a[maxindex],c);
return 0;
}

本文介绍了一种通过排序和遍历来找出数组中出现次数最多的元素的方法,并提供了一个使用 C 语言实现的具体示例。
1469

被折叠的 条评论
为什么被折叠?



