map和set

本公司现在要给公司员工发波福利,在员工工作时间会提供大量的水果供员工补充营养。由于水果种类

比较多,但是却又不知道哪种水果比较受欢迎,然后公司就让每个员工报告了自己最爱吃的k种水果,
并且告知已经将所有员工喜欢吃的水果存储于一个数组中。然后让我们统计出所有水果出现的次数,并
且求出大家最喜欢吃的前k种水果。
统计次数+排序

struct CountVal  //仿函数
{
	bool operator()(const pair<string, int>& l, const pair<string, int>& r)
	{
		return l.second > r.second;
	}
};

void GetFavoriteFruit  (const vector<string>& fruits ,int k)
{
	//先统计次数
	map<string, int> countMap;
	for (auto& str : fruits)
	{
		countMap[str]++;
	}
	//大家最喜欢吃的前k个
	//方法1:针对数据量不大 sort,<k,v>,里面的v不能直接进行排序,需要先将其放入vector
	vector<pair<string, int>> sortV;
	for (auto& kv : countMap)
	{
		sortV.push_back(kv);
	}
	sort(sortV.begin(), sortV.end(),CountVal());

	for (int i = 0; i < k; i++)
	{
		cout << sortV[i].first << ":" << sortV[i].second << endl;
	}

	cout << endl;
}

int main()
{
	//test_queue();
	//test_priority_queue();
	/*test_map2();*/

	vector<string> v = { "苹果", "苹果", "香蕉", "苹果", "香蕉", "哈密瓜", "番茄", "哈密瓜" };
	GetFavoriteFruit(v , 3);

	return 0;
}

前k个高频单词

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string,int> countMap;
        for(auto& str:words)
        {
            countMap[str]++;
        }

        multimap<int ,string,greater<int>> sortMap;//加了greater后从大到小排列
        for(auto& kv:countMap)
        {
            sortMap.insert(make_pair(kv.second,kv.first));
        }

        vector<string> v;
        auto it =sortMap.begin();
        while(k--)
        {
            v.push_back(it->second);  //将string压入v中
            ++it;
        }

        return v;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值