给定一组整型数据,找出其中出现次数最多的数据,如果出现次数最多的整数不唯一,则找出最大
的数据,记为M。找出其中出现次数最少的数据,如果出现次数最少的整数不唯一,则找出最小的
数据,记为N。最后求解M-N。
放上写的很low的c++代码
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
void test(int n) {
vector<int> res(n); // 所有数据存在这里
for (int i = 0; i < n; i++) {
cin >> res[i]; // 输入数据
}
// 统计出现次数
map <int, int> mp;
for (int i = 0; i < n; i++) {
mp[res[i]]++;
}
// 打印输出,可以注释掉
for (auto it = mp.begin(); it != mp.end(); it++) {
cout << "key = " << it->first << ", value = " << it->second << endl;
}
// 用tmp1存储mp的数据
std::vector<std::pair<int, int>> tmp;
for (auto& i : mp)
tmp.push_back(i);
// 对tmp的数据按照value(次数)排序
std::sort(tmp.begin(), tmp.end(),
[=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second > b.second; });
// 排完序后,首先是按照出现次数降序排序,出现次数相同的话,按照数值升序排序
cout << "******************************" << endl;
// 再次输出
for (auto it = tmp.begin(); it != tmp.end(); it++) {
cout <<"key = "<< it->first << ", value = " << it->second << endl;
}
int count = tmp[0].second; // 此时tmp存储的是出现次数最多,但数值最小的数据
int maxData = tmp[0].first;
for (auto it = tmp.begin() + 1; it != tmp.end(); it++) {
if (it->first == count) {
maxData = it->first; // 找出大的数值
}
}
cout << maxData << endl;
// 同样的方法处理找次数出现最少且最小的数据
std::vector<std::pair<int, int>> tmp2;
for (auto& i : mp)
tmp2.push_back(i);
std::sort(tmp2.begin(), tmp2.end(),
[=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; });
// 排完序后,先按照出现次数升序排序,出现次数相同的话,安装数值升序排序
cout << "******************************" << endl;
for (auto it = tmp2.begin(); it != tmp2.end(); it++) {
cout << "key = " << it->first << ", value = " << it->second << endl;
}
cout << tmp2[0].first << endl;
cout << maxData - tmp2[0].first << endl;
}
int main(int argc, char** argv) {
int n;
cin >> n;
test(n);
system("pause");
return 0;
}
测试
出现次数最多的是1和3,最大值是3;
出现次数最少的是4和5,最小的是4;
3-4=-1。
出现最多的数据是1和3,最大的数据是3;
出现最少的数据是4和5,最小的数据是4;
3-4=-1。
感受:
(1)这道题的难点在于去重。我这里利用map按照key升序排序的特性投机取巧了。
(2)利用vector<pair<int, int>> tmp取代map的数据,对tmp进行操作。