AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

自定义优先队列比较的元素(LC692 Top K Frequent Words为例)

作者: 作者的头像   格莱 ,  2020-01-02 03:15:53 ,  所有人可见 ,  阅读 961


0


692. Top K Frequent Words

class Solution {
typedef pair<string, int> tp;
public:
    struct cmp {
        bool operator()(const tp &a, const tp &b) const{
            if(a.second < b.second) return true;
            else if(a.second == b.second) {
                int t = strcmp(a.first.c_str(), b.first.c_str());
                if(t < 0) return false;
                else return true;
            } else {
                return false;
            }
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> wtf;
        vector<string> res;
        for(auto w: words) {
            if(wtf[w]) wtf[w]++;
            else wtf[w] = 1;
        }

        priority_queue<tp, vector<tp>, cmp> pq;

        for(auto i = wtf.begin(); i != wtf.end(); i++) {
            pq.push(make_pair(i->first, i->second));
        }

        for(int i = 0; i < k; i++) {
            res.push_back(pq.top().first);
            pq.pop();
        }
        return res;
    }
};

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息