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

问题:统计大家最爱玩的前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;
}

测试结果:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值