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

字符串出现次数的TopK问题

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

#include <queue>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * return topK string
     * @param strings string字符串vector strings
     * @param k int整型 the k
     * @return string字符串vector<vector<>>
     */
    struct Compare {
        bool operator()(const pair<string, int>& a, const pair<string, int>& b) {
            if (a.second == b.second) {
                return a.first < b.first;
            }
            return a.second > b.second;
        }
    };
    vector<vector<string> > topKstrings(vector<string>& strings, int k) {
        // write code here
        if (strings.size() == 0) {
            return {};
        }

        unordered_map<string, int> countMap;
        for (auto& str : strings) {
            countMap[str]++;
        }

        priority_queue<pair<string, int>, vector<pair<string, int>>, Compare> prq;
        vector<vector<string>> result;

        for (auto& [str, count] : countMap) {
            if (prq.size() < k) {
                prq.push({str, count});
            } else {
                pair<string, int> curr{str, count};
                if (count > prq.top().second 
                || (count == prq.top().second && str < prq.top().first)) {
                    prq.pop();
                    prq.push(curr);
                }
            }
        }

        while (!prq.empty()) {
            vector<string> vec;
            vec.push_back(prq.top().first);
            vec.push_back(to_string(prq.top().second));
            result.push_back(vec);
            prq.pop();
        }
        
        reverse(result.begin(), result.end());

        return result;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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