寻找整型数组中出现次数最多的数

1.先排序,然后再遍历,寻找出现次数最多的数

void f1(int *num,int length)
{

quickSort(num,0,length-1);
int max=0;//最大出现次数
int cur=1;//当前出现次数
int max_num=num[0];//出现次数最多的数字

//开始遍历查找出现次数最多的数字
for(int i=0;imax)
        {
            max=cur;
            max_num=num[i];
        }
        cur=1;
    }
    
}
cout<<"出现次数最多的数字是:"<

我们用max_num表示出现次数最多的数字,用max表示最大出现次数,用cur_max表示当前数字的出现次数,在遍历中逐步更新max的值,从而得到结果。

但是,如果有多个数字出现次数相同(且为最大出现次数),这时要想全部输出怎么办呢?

2.利用map

void f2(int *num,int length)
{
//key表示数字,value记载数字出现次数
map map_int;
for(int i=0;ifirst;//表示数字
int max=(map_int.begin())->second;//表示出现次数
for(map::iterator iter=map_int.begin(); iter!=map_int.end() ; iter++)
{
    if(iter->second > max)//找到了出现次数更多的值
    {
        value=iter->first;
        max=iter->second;
    }
}
cout<<"出现次数最多的数字是:"<

你可能感兴趣的:(寻找整型数组中出现次数最多的数)