问题描述
给定n个整数,请统计出每个整数出现的次数,按出现次数从多到少的顺序输出。
输入格式
输入的第一行包含一个整数n,表示给定数字的个数。
第二行包含n个整数,相邻的整数之间用一个空格分隔,表示所给定的整数。
输出格式
输出多行,每行包含两个整数,分别表示一个给定的整数和它出现的次数。按出现次数递减的顺序输出。如果两个整数出现的次数一样多,则先输出值较小的,然后输出值较大的。
样例输入
12
5 2 3 3 1 3 4 2 5 2 3 5
样例输出
3 4
2 3
5 3
1 1
4 1
评测用例规模与约定
1 ≤ n ≤ 1000,给出的数都是不超过1000的非负整数。
思路:
1、用一个哈希表存储每个整数和每个整数的次数。
2、由于哈希表不能直接进行排序,我们将哈希表的值转移到对数组中,对数组进行排序,对数组就是一个容器,但他的类型是一个对。
3、自定义sort的排序规则。
4、输出对数组。
代码实现:
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
bool order(pair<int, int>a, pair<int, int>b)
{
if (a.second > b.second)
return true;
else if (a.second < b.second)
return false;
else if (a.first < b.first)
return true;
return false;
}
int main() {
int n;
vector<pair<int, int>>res;
unordered_map<int, int>map;
cin >> n;
while (n--)
{
int j;
cin >> j;
++map[j];
}
for (auto s : map)
res.push_back({ s.first,s.second });
sort(res.begin(), res.end(), order);
for (auto s : res)
cout << s.first << " " << s.second << endl;
return 0;
}