本公司现在要给公司员工发波福利,在员工工作时间会提供大量的水果供员工补充营养。由于水果种类
比较多,但是却又不知道哪种水果比较受欢迎,然后公司就让每个员工报告了自己最爱吃的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;
}
};