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

字符串出现次数的TopK问题

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

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * return topK string
     * @param strings string字符串vector strings
     * @param k int整型 the k
     * @return string字符串vector<vector<>>
     */
    struct Node {
        string key;
        int cnt;
        Node(string k, int c): key(k), cnt(c) {}
        bool operator<(const Node& r) const {
            if (cnt != r.cnt) {
                return cnt > r.cnt;
            }
            return key < r.key;
        }
    };
    vector<vector<string> > topKstrings(vector<string>& strings, int kk) {
        unordered_map<string, int> hash;
        priority_queue<Node> q;
        for (auto& s : strings) hash[s]++;
        for (auto &[k, v] : hash) {
            Node node(k, v);
            q.push(node);
            if(q.size() > kk) q.pop();
        }
        vector<vector<string> > ans;
        while(q.size()){
            ans.push_back({q.top().key,to_string(q.top().cnt)});
            q.pop();
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

全部评论

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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