出现次数的TopK问题

出现次数的TopK问题

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

#include <unordered_map>
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
        vector<vector<string> > ans;
        if (strings.size() == 0 || strings.size() < k)
            return ans;
        // 记录每个元素出现的次数
        unordered_map<string, int> hash;
        for (const auto& string : strings) {
            hash[string]++;
        }
        // 建立小根堆,按照出现次数排序,次数相同按照字典序
        auto cmp = [](const pair<string, int>& p1, const pair<string, int> p2) {
            if (p1.second != p2.second)
                return p1.second > p2.second;
            return p1.first < p2.first;
        };
        // 将全部元素入堆
        priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> max_heap(cmp);

        auto p_iter = hash.begin();

        for ( ; p_iter != hash.end(); p_iter++) {
            max_heap.emplace(*p_iter);
            if (max_heap.size() > k)
                max_heap.pop();
        }

        while (!max_heap.empty()) {
            pair<string, int> p = min_heap.top();
            max_heap.pop();
            ans.insert(ans.begin(), vector<string>{p.first, to_string(p.second)} );
        }

        return ans;

    }
};
全部评论
这个代码里是最小堆吧,max_heap名字可以改一改
点赞
送花
回复
分享
发布于 2021-04-12 11:02
好的感谢
点赞
送花
回复
分享
发布于 2021-05-12 19:12
滴滴
校招火热招聘中
官网直投

相关推荐

2 1 评论
分享
牛客网
牛客企业服务