众数(哈尔滨工业大学)

众数

题目描述

输入20个数,每个数都在1-10之间,求1-10中的众数(众数就是出现次数最多的数,如果存在一样多次数的众数,则输出权值较小的那一个)。

输入描述

测试数据有多组,每组输入20个1-10之间的数。

输出描述

对于每组输入,请输出1-10中的众数。

示例1

输入

5 1 5 10 3 5 3 4 8 6 8 3 6 5 10 7 10 2 6 2

输出

5

1.双数组法
数组的值存放出现的次数,数组下标存放对应的数。

#include<iostream>
#include<cstring>
//#include<cstdio>
using namespace std;
int a[11],b[21];
int main()
{
 	//freopen("C:\\Users\\lenovo\\Downloads\\in.txt","r",stdin);
 	int max,max_n;
 	while(cin >> b[0])
 	{
  		for(int i=1; i<20; ++i)
  		{
   			cin >> b[i];
  		}
  		for(int i=0; i<20; ++i)
  		{
   			a[b[i]]++;
  		}
  		max=a[1],max_n=1;
  		for(int i=2; i<=10; ++i)
  		{
   			if(a[i]>max)
   			{
    				max=a[i];
    				max_n=i;
   			}
  		}
  		cout << max_n << endl;
  		memset(a,0,sizeof(a));
  		memset(b,0,sizeof(b));
 	}
 	return 0;
}

双数组法另一种写法:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
 	//freopen("C:\\Users\\lenovo\\Downloads\\in.txt","r",stdin);
 	int a[11]={0},b[21]={0};
 	int max,max_n;
 	while(scanf("%d",&b[0]) != EOF)
 	{
  		a[b[0]]++;
  		for(int i=1; i<20; ++i)
  		{
   			scanf("%d",&b[i]);
   			a[b[i]]++;
  		}
  		max=a[1],max_n=1;
  		for(int i=2; i<=10; ++i)
  		{
   			if(a[i]>max)
   			{
   	 			max=a[i];
    				max_n=i;
   			}
  		}
  		printf("%d\n",max_n);
  		memset(a,0,sizeof(a));
  		memset(b,0,sizeof(b));
 	}
 	return 0;
}

这里需要注意一下,数组元素全部清0要用memset()函数。

 memset(a,0,sizeof(a));
 memset(b,0,sizeof(b));

切记不能够这样:

a[11]={0};
b[21]={0};

a[11]和b[21]代表一个元素,不再是一个数组了,而且是一个越界的元素。

int a[11]={0};
int b[21]={0};

上述定义数组并且所有元素初始化为0。而下面做法显而易见是错误的:

int a[11],b[21];
a[11]={0},b[21]={0};

2.map大法

代码如下:

#include<iostream>
#include<map>
//#include<cstdio>
using namespace std;
map<int,int> mp;
map<int,int>::iterator it;
int main()
{
 	//freopen("C:\\Users\\lenovo\\Downloads\\in.txt","r",stdin);
 	int k;
 	while(cin >> k)
 	{
  		mp[k]++;
  		for(int i=1; i<20; ++i)
  		{
   			cin >> k;
   			mp[k]++;
  		}
  		int max=0,max_n=0;
  		for(it=mp.begin(); it!=mp.end(); ++it)
  		{
   			if(it->second>max)
   			{
    				max=it->second;
    				max_n=it->first;
   			}
  		}
  		cout << max_n << endl;
  		//mp.erase(mp.begin(),mp.end());
  		mp.clear();
 	}
 	return 0;
}

这里也说明一下清空map里面所有元素的两种写法:
1.mp.clear(),它会删除mp里面的所有元素。
2.mp.erase(mp.begin(),mp.end()),用迭代器范围删除,把整个mp清空。

感谢观看!
题目来源于牛客网的计算机历年考研复试上机题,附上网址:
https://www.nowcoder.com/ta/kaoyan

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39229079/article/details/105508720