您的位置:首页 > 运维架构

TopK问题——统计大家最爱玩的游戏

2017-06-29 10:04 260 查看
问题:统计大家最爱玩的前K种游戏

思路:大体思路是用库里的map来存放数据pair< string,int>可以统计。然后再比较int的值建大堆,堆排序之后取出前K的元素,存放在数组里返回。

代码:

//核心代码
#include<algorithm>
#include<map>
#include<string>
#include<vector>
using namespace std;
class Greater
{
public:
bool operator()(pair<string, int>p1, pair<string, int>p2)
{
return p1.second > p2.second;//重载(),注意要比较second的值大小。
}
};
vector<string> FavoriteGamesTopK(vector<string>& game , int K)
{
vector<string>TopKGame;
map<string, int> Countmap;//创建数据结构存储数据
map<string, int>::iterator It;//设置迭代器遍历
for (size_t i = 0; i < game.size(); ++i)
{
//方案一 判断插入
It = Countmap.find(game[i]);
if (It != Countmap.end())
{
//找到
It->second++;
}
else
Countmap.insert(pair<string, int>(game[i],1));
//方案二 用operator[]插入。
//Countmap[game[i]]++;
//operator[]底层实现是用insert,也就是判断有就给sceond++,没有就插入。
}
vector<pair<string,int>> heap;
heap.insert(heap.begin(),Countmap.begin(), Countmap.end());//把Countmap的元素插入到heap中
make_heap(heap.begin(),heap.end(),Greater());//建立大堆 这里默认的缺省值为less,就是小堆,所以自己给出了仿函数Greater()来实现建立大堆
sort_heap(heap.begin(), heap.end(), Greater());
for (int i = 0; i <K; ++i)//取出前K的元素
{
TopKGame.push_back(heap[i].first);
}
return TopKGame;
}


测试:

void TestGetTopK()
{
vector<string> games;
games.push_back("英雄联盟");
games.push_back("王者荣耀");
games.push_back("王者荣耀");
games.push_back("DNF");
games.push_back("CS:GO");
games.push_back("英雄联盟");
games.push_back("王者荣耀");
games.push_back("DNF");
games.push_back("王者荣耀");
games.push_back("data2");
games.push_back("data2");
games.push_back("魔法王座");
games.push_back("贪玩蓝月");
games.push_back("英雄联盟");
vector<string> ret=FavoriteGamesTopK(games,5);//K=5
for (int i = 0; i < ret.size(); ++i)
{
cout <<"Top "<<i+1<<":"<< ret[i] <<endl ;
}
}
int main()
{
TestGetTopK();
return 0;
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: