問題描述:
給定 nn 個整數,求裡面出現次數最多的數,如果有多個重複出現的數,求出值最大的一個。
輸入格式
第一行輸入一個整數 n(1 \le n \le 100000)n(1≤n≤100000),接下來一行輸入 nn 個 int 範圍内的整數。
輸出格式
輸出出現次數最多的數和出現的次數,中間用一個空格隔開,如果有多個重複出現的數,輸出值最大的那個。
樣例輸入1
5
1 1 2 3 4
樣例輸出1
1 2
樣例輸入2
10
9 10 27 4 9 10 3 1 2 6
樣例輸出2
10 2
代碼解析:
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n;//輸入個數
cin>>n;
map<int, int> set;//第一個參數表示數字,第二個參數表示次數
//插入和計數
for(int i=0; i<n; i++)//輸入
{
int number;
cin>>number;
//如果第一次插入
if(!set.count(number))set.insert(pair<int,int>(number,1));
else set[number]++;
}
//确定最大值
int maxans=0;
for(map<int,int>::iterator it=set.begin(); it!=set.end(); it++)
{
if(it->second>maxans)
{
maxans=it->second;
}
}
//輸出
int digit=1;
for(map<int,int>::iterator it=set.begin(); it!=set.end(); it++)
{
if(it->second==maxans)
{
digit=it->first;
for(map<int,int>::iterator it2=set.begin(); it2!=set.end(); it2++)
{
if(it2->second==maxans)
{
if(it->first<it2->first)
{
digit=it2->first;
}
}
}
}
}
cout<<digit<<" "<<maxans<<endl;
return 0;
}