一.问题描述
给定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的非负整数。 数组运用题目 思路:数组下标作为输入的整数,数组元素作为其下标整数出现的次数。 关键在输出时的方法,先倒序循环出现的次数最大出现次数不过1000次,再从小到大循环下标,有出现次数与数组元素相同的就输出 下标和出现次数。这样就满足了题中要求。
二.代码
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<
int,
int> PAIR;
bool com(
const PAIR &l,
const PAIR &r){
if(l.second==r.second){
return l.first<r.first;
}
else{
return l.second>r.second;
}
}
int main(){
int len;
map<int,int> container;
cin>>len;
cin.ignore();
for(
int i=
0; i<len; i++){
int tem;
cin>>tem;
++container[tem];
}
vector<PAIR> vec(container.begin(),container.end());
sort(vec.begin(),vec.end(),com);
for(
int j=
0; j<vec.size(); j++){
cout<<vec[j].first<<
" "<<vec[j].second<<endl;
}
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-1311591.html