取出现次数最多的最大值和出现次数最少的最小值

给定一组整型数据,找出其中出现次数最多的数据,如果出现次数最多的整数不唯一,则找出最大

的数据,记为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进行操作。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值