求整数序列中出现次数最多的数
思路:先将n个整数输入进数组,再将数组从小到大进行排序,再比较出现次数最多得数,难点是最后一步:比较出现次数最多得数,读者可以随意写出n个整数,再对代码进行解读,更容易理解
#include <stdio.h>
int main()
{
int arr[1000] = { 0 };
int n = 0;
int i = 0;
int j = 0;
int i1 = 0;
int count1 = 0;
int count = 0;
int temp = 0;
scanf("%d",&n);
for( i = 0 ; i < n ; i++ )
{
scanf("%d",&arr[i]);
}
if( n == 1 )
{
printf("%d %d",arr[0],1);
return 0;
}
else
{
for( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < n - i - 1; j++ )
{
if( arr[j] > arr[j+1] )
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for( i = 0 ; i < n - 1 ; i++ )
{
if( arr[i] != arr[i+1] )
{
count++;
if( count > count1 )
{
i1 = i;
count1 = count;
}
count = 0;
}
else
{
if( i != n -2 )
{
count++;
continue;
}
else
{
count = count + 2;
if( count > count1 )
{
i1 = i;
count1 = count;
}
}
}
}
printf("%d %d",arr[i1],count1);
return 0;
}
}