试题编号: | 201312-1 |
---|---|
试题名称: | 出现次数最多的数 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s 1, s 2, …, s n (1 ≤ s i ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10
|
思路分析:
其实最主要的就是统计数字出现的次数,每次新输入的数字都和前面存储的数字进行比较,如果已经存在,那么对应的数字的times加一,最后比较每个数字的times,在times相同的情况下比较数字的大小。
代码:
#include<iostream>
using namespace std;
int main() {
typedef struct {
int number;//存储数字
int times;//记录数字出现的次数
} Data;
typedef struct {
Data data[1001];
int listlen;
} SL;//存放数字
SL sllist;
sllist.listlen = 0;//初始化数组
int n, outt, outn;
cin >> n;//输入数字个数n
for (int i = 0; i < n; i++) {
cin >> sllist.data[i].number;
sllist.data[i].times = 1;
sllist.listlen++;
//当输入数字个数大于1时,每输入一个新数字,都依次与数组中的每一个数字进行比较,如果是出现过的数字,那么该数字的每一个存储位置对应的次数加1
示例见后面结果
if (i >= 1) {
for (int j = i - 1; j >= 0; j--) {
if (sllist.data[i].number == sllist.data[j].number) {
sllist.data[j].times++;
}
}
}
}
outn = sllist.data[0].number;
outt = sllist.data[0].times;
//比较判断找出出现次数最多同时最小的数字
for (int k = 1; k <= sllist.listlen; k++) {
if (sllist.data[k].times >= outt) {
if(sllist.data[k].times > outt){
outt=sllist.data[k].times;
outn = sllist.data[k].number;
}
if (sllist.data[k].times == outt && sllist.data[k].number < outn) {
outn = sllist.data[k].number;
outt=sllist.data[k].times;
}
}
}
cout<<outn;
return 0;
}
计数的方式:
最后得分:
其实我还是不是很明白为什么测试结果错误,在自己的Clion编译环境中测试结果完全OK,希望大家多多指教。
后面去看了下其他的答案,确实更加科学和有效,官方给出的参考答案用到了map,因为数字范围较小,可以只利用一个数组Arr[],输入数字m,则对应Arr[m]++;Arr[m]的值就是对应数字m出现的次数,当次数相同时,因为按照循环是从0开始依次比较,所以这时返回的最小值为对应数组Arr[m]的序号m,不用进行更改和替换。
代码如下:
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
cin >> n;
map<int, int> f;
for (int i = 0; i < n; i++){
int t;
cin >> t;
f[t]++;
}
int ans, m = 0;
for (map<int, int>::iterator it = f.begin(); it != f.end(); it++) {
if (it->second > m) {
m = it
->second;
ans = it
->first;
}
}
cout << ans << endl;
return 0;
}