题解 | #字符串出现次数的TopK问题#

字符串出现次数的TopK问题

http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee

#define PSI pair<string,int>
class mycompare{
public:
    //小顶堆:使用的是greater比较方法,也就是谁的优先级大,就返回谁
    //那么这里首先频率大的就是greater,其次字典序小的就是greater。
    //所以我们这里使用的compare,就是根据这个greater思想来写的
    bool operator()(const PSI &lhs,const PSI &rhs){
        if(lhs.second > rhs.second)return true;
        if(lhs.second == rhs.second)return lhs.first < rhs.first;
        return false;
    }
};
class Solution {
public:
    /**
     * return topK string
     * @param strings string字符串vector strings
     * @param k int整型 the k
     * @return string字符串vector<vector<>>
     */
    vector<vector<string> > topKstrings(vector<string>& strings, int k) {
        // write code here
        unordered_map<string,int> counts;
        for(auto &element : strings){
            ++counts[element];
        }
        priority_queue<PSI,vector<PSI>,mycompare> pq;
        for(auto &element : counts){
            if(pq.size() < k)pq.push(element);
            else if(mycompare()(element,pq.top())){
                pq.pop();pq.push(element);
            }
        }
        vector<vector<string>> ans(k);
        int index = 0;
        while(!pq.empty()){
            auto current = pq.top();pq.pop();
            ans[--k] = {current.first,to_string(current.second)};
        }
        return ans;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 12:05
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务