zoukankan      html  css  js  c++  java
  • 692. 前K个高频单词

    692. 前K个高频单词

    涉及到一个自定义heap

    struct cmp{
        template<typename T, typename U>
        bool operator()(T const& left, U const& right){
            if(left.second>right.second||(left.second==right.second&&left.first<right.first))
                return true;
            return false;
        }
    };
    
    priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> minHeap;

    代码如下:

    class Solution {
    public:
    struct cmp{
        template<typename T, typename U>
        bool operator()(T const& left, U const& right){
            if(left.second>right.second||(left.second==right.second&&left.first<right.first))
                return true;
            return false;
        }
    };
        vector<string> topKFrequent(vector<string>& words, int k) {
            priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> minHeap;
            unordered_map<string, int> mp;
            for(string& s:words)
                mp[s]++;
            for(auto& item:mp){
                if(minHeap.size()<k){
                    minHeap.push(make_pair(item.first,item.second));
                }
                else if(item.second>=minHeap.top().second){
                    if(item.second==minHeap.top().second&&item.first>=minHeap.top().first)continue;
                    minHeap.pop();
                    minHeap.push(make_pair(item.first,item.second));
                }
            }
            vector<string> ans;
            while(!minHeap.empty()){
                ans.push_back(minHeap.top().first);
                minHeap.pop();
            }
            reverse(ans.begin(), ans.end());
            return ans;
        }
    };
  • 相关阅读:
    KINDLE 小说下载--超级书库
    修改PR Cs6,PS Cs6,AU Cs6的启动界面
    SQLMAP用户手册
    Burp Suite 实战指南--说明书
    XSS跨站测试代码
    万能密码字典
    python数据结构之队列(一)
    python数据结构之栈
    python实现链表(二)
    python实现链表(一)
  • 原文地址:https://www.cnblogs.com/Dancing-Fairy/p/13027415.html
Copyright © 2011-2022 走看看