数组中寻找出现次数最多的一个数

//第一种方法
#include
#include<stdlib.h>
using namespace std;
//以空间换取时间
//时间复杂度分析2n1+2n2
//空间复杂度为n2
int search(int* a, int len)
{
int tmp[100] = {0};
int key = 0;
int max = 0;
int index=0;
for (int i = 0; i < len; i++)//2n1
{
key = a[i];
tmp[key]++;
}
for (int i = 0; i < 100; i++)//2n2
{
if (max < tmp[i])
{
max = tmp[i];
index=i;
}
}
return index;
}
void main()
{
int a[1000] = { 0 };
for (int i = 0; i < 1000; i++)
{
a[i] = rand()%100;
}
cout << “出现次数最多的数为:” << search(a, 1000) << endl;
system(“pause”);
}

//第二种方法
#include
#include<stdlib.h>
#include
using namespace std;
//时间复杂度分析n
//空间复杂度分析<n
//时间换空间
int search(int *a, int len)
{
map<int,int> tmp;
for (int i = 0; i < len; i++)
{
pair<map<int,int>::iterator,bool> pairit=tmp.insert(pair<int,int>(a[i],1));
if (!pairit.second)
{
tmp[a[i]]++;
}
}
int max = 0;
int num = 0;
for (int i = 0; i <len; i++)
{
if (max < tmp[a[i]])
{
max = tmp[a[i]];
num = a[i];
}
}
return num;
}

void main()
{
int a[1000] = { 0 };
for (int i = 0; i < 1000; i++)
{
a[i] = rand() % 100;
}
cout << “出现次数最多的数为:” << search(a, 1000) << endl;
system(“pause”);
}

猜你喜欢

转载自blog.csdn.net/weixin_40677431/article/details/82828957
今日推荐