题目:
问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
10 1 10 20 30 20
样例输出
10
——————————————————————————————————————————————————————
这道题使用 map 即可 ( 容量大小不用事先声明 ,初始值默认为0 )
1 #include<stdio.h> 2 #include<iostream> 3 #include<vector> 4 #include<map> 5 6 using namespace std; // 7 8 int main() 9 { 10 map<int,int>m; // 如果不指定大小 ?? 11 int n; 12 cin>>n; 13 14 vector<int>val; 15 16 // m[2] = 2; 17 // m[1] = 4; 18 // 19 // for (map<int,int>::iterator it = m.begin();it!=m.end();it++) ///map 如何 迭代器取值 20 // { 21 // cout<<it->first<<" "<<it->second<<endl; 22 // } 23 24 for (int i=0;i<n;i++) 25 { 26 int v; 27 cin>>v; 28 m[v]++; 29 30 val.push_back(v); 31 } 32 33 int ans; 34 int cnt=0; 35 36 // for (int i=0;i<m.size();i++) 37 // { 38 // 39 // int tmp = val[i]; 40 // int tmp_cnt = m[tmp]; 41 // 42 // if (tmp_cnt>cnt) 43 // { 44 // cnt = tmp_cnt; 45 // ans = 46 // } 47 // } 48 49 50 for (map<int,int>::iterator it = m.begin();it!=m.end();it++) ///map 如何 迭代器取值 51 { 52 int tmp = it->second; 53 if (tmp>cnt) 54 { 55 cnt = tmp; 56 ans = it->first; 57 } 58 } 59 60 cout<<ans; 61 62 return 0; 63 }